一、行内元素
1.水平居中
原始代码:
<div class="parent">
<span class="child">content</span>
</div>
.parent{
width: 400px;
height: 100px;
background-color: antiquewhite;
}
.child{
background-color: aqua;
}
(1)text-align: center;
.parent{
text-align: center;
}
效果:实现水平居中
(2)width: fit-content;
相对于body水平居中
.parent{
width: fit-content;
margin: auto;
}
效果:
2.垂直居中
目标效果:
line-height: 父模块高度;
.parent{
line-height: 100px;
}
二、块级元素
原始代码
<div class="parent">
<div class="child">content</div>
</div>
.parent{
width: 400px;
height: 100px;
background-color: antiquewhite;
}
.child{
width: 100px;
height: 50px;
background-color: aqua;
}
1.水平居中
目标效果:
margin: 0 auto;
使其左右自适应
.child{
margin: 0 auto;
}
2.水平垂直居中
目标效果:
(1)通过定位实现
注意:子绝父相
思路:
先用left和top属性位移父模块的50%,然后反向移动自身的一半,来达到效果。
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -50px;
}
或者使用:
left: calc(50% - 50px);
top: calc(50% - 25px);
(2)通过定位+tranform
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
(3)定位+margin
原理:将left,top,right和bottom设置为0,此时子元素就会填充父元素的所有可用空间,在水平垂直方向上就有了可分配的空间,然后设置margin:auto;即可达到效果。
.parent{
position: relative;
}
.child{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
(4)通过flex
.parent{
display: flex;
align-items: center;
justify-content: center;
}
(5)通过伪元素
原理:
先将子元素设置为行内元素,使text-align: center;达到水平居中的效果,然后设置父元素::before,::before默认是行内元素,设置宽高是无效的,所以改成行内块元素,使子元素和::before并排排列,然后二者都设置vertical-align: middle;来达到效果。
.parent{
text-align: center;
}
.child{
display: inline-block;
vertical-align: middle;
}
.parent::before{
content: "";
display: inline-block;
width: 1px;
height: 父元素高度;
vertical-align: middle;
}