2个div在一个容器,其中一个如何自动垂直居中
在DIV0中有两个DIV,其中DIV1固定,DIV2高度会根据内容变化,DIV1如何在DIV0中垂直居中。
CSS设置为:
DIV0{
height: 100%;
width: 100%;
position: relative;}
DIV1{
width: 14%;
height: 14%;
display: inline-block;
}
DIV2{
display: inline-block;
position: absolute;
height: 100%;}
<!doctype html>
<style>.wrap{width:640px;margin:50px auto}
#DIV0 {
height: 100%;
width: 100%;
position: relative;
background: #ccc;
padding: 100px;
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box
}
#DIV1, #DIV2 {
width: 200px;
height: 200px;
display: inline-block;
background: blue
}
#DIV2 {
height: auto;/*自动高度*/
background: yellow
}
</style>
<div class="wrap">
<div id="DIV0">
<div id="DIV1"></div>
<div id="DIV2">
1<br />2<br />3<br />
1<br />2<br />3<br />
1<br />2<br />3<br />
1<br />2<br />3<br />
1<br />2<br />3<br />
1<br />2<br />3
</div>
</div>
</div>
DIV0 {
height: 100%;
width: 100%;
position: relative;
}
DIV1 {
width: 14%;
height: 14%;
display: flex; /* 将display属性改为flex */
align-items: center; /* 垂直居中 */
}
DIV2 {
display: inline-block;
position: absolute;
height: 100%;
left: 14%; /* 与DIV1相距14% */
top: 0;
bottom: 0;
right: 0;
}
DIV0{
height: 100%;
width: 100%;
display: flex;
align-items: center;
}
DIV1{
width: 14%;
height: 14%;
}
DIV2{
height: 100%;}
div2动态宽度通过css样式比较难控制,除非用js来控制,建议使用定宽度来实现水平居中
比如:width:80%;position: absolute;height: 100%;top:0px;left:50%;margin-left:-40%;