Css 如何在居中div下方居中div?
我基本上有3个主要div:外部div、第一div和第二divCss 如何在居中div下方居中div?,css,Css,我基本上有3个主要div:外部div、第一div和第二div <div class = "outer"> <div class = "first"> </div> <div class = "second"> </div> </div> 因为一开始我只关注第一个分区的中心。我没有提前考虑并计划创建第二个分区 <div class = "outer"> <div
<div class = "outer">
<div class = "first">
</div>
<div class = "second">
</div>
</div>
因为一开始我只关注第一个分区的中心。我没有提前考虑并计划创建第二个分区
<div class = "outer">
<div class = "first">
</div>
<div class = "second">
</div>
</div>
无论如何,第二个div当前显示在第一个div的左上角,我希望它在水平居中时显示在第一个div的下方,但我不知道该怎么做。我尝试在第二个div中添加一个clear:tware,希望它“清除”第一个div,以便它可以移动到它下面,但这没有起作用 试试这个:
.first {
margin-right: auto;
margin-left: auto;margin-top:0.3em;
min-height: 14em;
width: 46%;
background: red;
}
.second{margin-right: auto;
margin-left: auto;
min-height: 14em;margin-top:0.3em;
width: 46%;background: blue;}
您不需要在第一个div上有一个“position:fixed”。如果出于某种原因您确实需要固定div,您可以将其添加到最外层的“outer”div。我在codepen中快速画笔,并将工作代码放在下面
.outer{
position:fixed;
width:100%;
}
.first {
margin:auto;
min-height: 14em;
width: 46%;
top: 5em;
}
.second{
width:46%;
height:50px;
margin:auto;
}
现在还不清楚您是否打算使用
position:fixed
,但我会假设您是
使用flexbox:
HTML
为什么要使用
位置:固定?其他元素将不知道在哪里。只要固定,first
就在页面上,因此除非,否则它们不会在页面周围流动。first
具有定义的高度,您可以手动将其他元素放置在其周围。您无法“清除”任何位置:固定的,这实际上没有任何意义。它本质上是定位到视口的绝对位置(而不是定位到最近的位置:相对的父对象)。关于position
属性-@michaelocker,这里有一篇相当不错的文章,我认为我使用它是错误的(我最初认为使用position:fixed会使div能够适应不同的屏幕大小或其他东西)。我现在把它拿走了!第一个div仍然保持居中,第二个div现在是第一个div的左下角。这就是你想要的吗?将某物水平居中的诀窍是给它一个宽度
,并使用左边距/右边距:自动
,就像您使用一样。首先
<div class="outer">
<div class="first">
</div>
<div class="second">
</div>
</div>
.outer {
display: flex;
flex-direction: column;
align-items: center;
}
.first, .second {
height: 200px;
width: 50vh;
}
.first {
position: fixed;
background-color: blue;
}
.second {
margin-top: 200px;
background-color: red;
}