方法一:将line-height设置成和height一致,text-align: center;【仅适用于文字】
<div>居中</div>
div {
width: 100px;
height: 100px;
background-color: rgb(121, 196, 247);
font-size: 20px;
/* 水平居中 */
text-align: center;
line-height: 100px;
}
方法二:使用flex弹性布局【文字和元素均适用】
设置 display:flex;justify-content:center;align-items:center; 即可可垂直水平居中
div {
width: 100px;
height: 100px;
background-color: rgb(146, 193, 224);
display: flex;
/* 主轴居中对齐 */
justify-content: center;
/* 侧轴居中对齐 */
align-items: center;
}
方法三:增加一个父元素,使用定位加位移(position和transform)【文字和元素均适用】
增加一个父元素(设置position: relative;),子元素(position: absolute; left: 50%; top:50%; transform: translate(-50%, -50%);),即可可垂直水平居中
<div class="one">
<div class="two">居中</div>
</div>
.one {
width: 500px;
height: 500px;
background-color: rgb(146, 193, 224);
/* 设置绝对定位的元素 */
position: relative;
}
.two {
/* 设置相对定位的元素 */
position: absolute;
left: 50%;
top: 50%;
/* 利用transform属性,将其往左平移span自身长度的50%,往上平移span自身长度的50% */
transform: translate(-50%, -50%);
}
方法四:增加一个父元素,使用定位+margin: auto;【仅适用于元素】
.one {
width: 300px;
height: 300px;
background-color: rgb(49, 134, 190);
/* 设置绝对定位的元素 */
position: relative;
}
.two {
/* 设置相对定位的元素 */
width: 100px;
height: 100px;
position: absolute;
background-color: rgb(146, 170, 185);
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
如有不同见解,欢迎讨论,更多情景,正在更新中。。。。。。