使用CSS将包含相对元素的DIV居中
Center a DIV containing relative element using CSS
我对这种行为很纠结。我在DIV容器中添加了两个DIV (sub1和sub2)。将Sub2设置为与Sub1右下角重叠的相对位置。这样做,容器DIV的宽度不是很好,它与改变Sub1的相对位置之前相同。起初,这没有问题,但后来,客户决定将整个东西居中,因此需要容器的实际宽度。
这可以通过CSS实现吗?即使在JavaScript中,我也得到了相同的宽度(错误的那个)。
下面是这个问题的一个简单例子:
html, body {
width:100%;
height: 100%;
}
#main {
position: fixed;
display: inline-block;
margin: auto;
}
#sub1 {
width: 100px;
height: 100px;
background-color:red;
position: relative;
}
#sub2 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 80px;
top: -20px;
}
<div id="main">
<div id="sub1">
</div>
<div id="sub2">
</div>
</div>
如果你想让你的容器div拥有两个块的宽度,你不应该使用相对定位。用边距代替
#sub2 {
width: 100px;
height: 100px;
background-color: blue;
margin-left: 80px;
margin-top: -20px;
}
我不太清楚您想看到什么样的行为。我想如果你想让红色和蓝色的方块重叠,但你也想让它们在页面中居中?在这种情况下,解决方案很简单,只需在"main"和较小的框之间添加另一个DIV图层。
html, body {
width:100%;
height: 100%;
}
#main {
position: fixed;
display: inline-block;
margin: auto;
width: 100%;
height: 100%;
}
#center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#sub1 {
width: 100px;
height: 100px;
background-color:red;
position: relative;
}
#sub2 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 80px;
top: -20px;
}
<div id="main">
<div id="center">
<div id="sub1">
</div>
<div id="sub2">
</div>
</div>
</div>
一般来说,对于你想要一个元素做的每一个"转换",你应该在它周围为那个转换添加另一个DIV包装器。这样,每个转换都是相互独立的,并且它们更容易管理。
这是一个流行的方法来居中任何元素(不添加更多的div):使用transform
属性与left
(或top
垂直居中)。
html, body {
width:100%;
height: 100%;
}
#main {
position: fixed;
width: 200px;
left: 50%;
transform: translateX(-50%);
}
#sub1 {
width: 100px;
height: 100px;
background-color:red;
position: relative;
}
#sub2 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 80px;
top: -20px;
}
<div id="main">
<div id="sub1"></div>
<div id="sub2"></div>
</div>
我还从#main{}
中删除了display: inline-block;
,因为它在这个演示中没有做任何事情。
相关文章:
- 添加文字和评论功能更新Div
- 点击后隐藏潜水?(但如果Div是一面旗帜呢?)
- 使用JavaScript动态插入DIV的成本有多高
- DIV并排,位置不正确
- Div根据<选择>菜单
- 将旋转的Div居中
- 用CSS居中内联块DIV“:在“;以垂直和水平为中心的废墟文本
- 在 Div 中垂直居中表格
- 如果元素变得比窗口宽,则在 DIV 中居中元素而不切断左侧内容
- DIV中具有最大宽度的居中图像
- 在垂直居中的 DIV 上设置最小顶部
- 使用 CSS 在 BODY 中垂直居中 DIV
- 如何在调整大小的DIV中居中并放大/缩小图像
- 当定位为绝对位置时,将DIV居中,并改变DIV中的内容
- CSS缩放Div居中
- 当移动页面位于顶部时,Div垂直居中,但当我们向下滚动页面时,会发生错误
- 粘贴导航条/居中Div的右侧
- 使用CSS将包含相对元素的DIV居中
- 父Div元素中的图像居中问题
- 引导导航栏居中,但DIV高于内容