我目前有3个元素通过flex在容器中垂直居中:
<div class="parent">
<div class="first">A</div>
<div class="second">B</div>
<div class="third">C</div>
</div>
使用CSS:
.parent {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 800px;
}
理想情况下,这可以简单地通过flex来完成,但是到目前为止我找不到解决方案。任何帮助表示赞赏。
答案 0 :(得分:0)
如果元素的大小固定,则可以使用div包装 大小与第一个元素相同,然后让随后的元素溢出。
.parent {
height: 125px;
background-color: palegreen;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.item-container,
.item {
width: 200px;
height: 30px;
}
.item {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid red;
}
.second {
height: 50px;
}
<div class="parent">
<div class="item-container">
<div class="item first">A</div>
<div class="item second">B</div>
<div class="item third">C</div>
</div>
</div>
答案 1 :(得分:0)
如果可以更改HTML结构,则可以:将第二个和第三个元素放入包装器DIV中,然后将其放入第一个。然后将第一个居中(不一定要使用flex-参见下文)并对其应用position: relative
,然后对包装器应用position: absolute
并根据位置设置。有关详细信息,请参见下面的代码段。
.parent {
height: 500px;
border: 1px solid blue;
}
.first {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 100px;
width: 300px;
background: #ccc;
}
.wrap1 {
position: absolute;
top: 100%;
width: 100%;
height: auto;
border: 1px solid green;
}
.second {
background: #eee;
height: 50px;
}
.third {
background: #aaa;
height: 80px;
}
<div class="parent">
<div class="first">A
<div class="wrap1">
<div class="second">B</div>
<div class="third">C</div>
</div>
</div>
</div>
添加:实际上,使用flex也可以实现
.parent {
height: 500px;
border: 1px solid blue;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.first {
position:relative;
height: 100px;
width: 300px;
background: #ccc;
}
.wrap1 {
position: absolute;
top: 100%;
width: 100%;
height: auto;
border: 1px solid green;
}
.second {
background: #eee;
height: 50px;
}
.third {
background: #aaa;
height: 80px;
}
<div class="parent">
<div class="first">A
<div class="wrap1">
<div class="second">B</div>
<div class="third">C</div>
</div>
</div>
</div>