水平居中、垂直居中,总有一款适合你的
一、子容器单纯只是内容,实现水平居中、垂直居中、或两者皆可
.parDiv { position: relative; text-align: center; width: 100%; height: 300px; line-height: 300px; background-color: green; } .chiDiv {}
效果图:
二、子容器有固定的宽高,实现水平居中、垂直居中、或两者皆可
.parDiv { position: relative; height: 300px; width: 100%; background-color: green; } .chiDiv { position: absolute; width: 100px; height: 100px; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; background-color: red; }
效果图:
三、子容器没有固定宽高,实现水平居中、垂直居中、或两者皆可(适合做弹框菜单)
方法一:
.parDiv { position: relative; height: 300px; width: 100%; background-color: green; } .chiDiv { position: absolute; top: 50%; left: 50%; background-color: red; transform: translateX(-50%) translateY(-50%); }
方法二:
.parDiv { width: 100%; height: 300px; display: flex; background-color: green; } .chiDiv { background-color: red; margin: auto; }
效果图:
四、父容器固定高度,子容器inline-block,可实现水平和垂直居中
.parDiv{
width: 400px;
height: 400px;
line-height: 400px;
text-align: center;
background-color: green;
}
.chiDiv{
display: inline-block;
line-height: normal;
background-color: red;
}
HTML代码:
<div class="parDiv"> <div class="chiDiv">子容器内容</div> </div>