HTML元素的⽔平垂直居中⽅式(简单代码和图)
1.⽔平居中text-align:center;
在没有浮动的情况下,我们可以让需要居中的块级元素设为inline/inline-block,然后在其⽗元素上添加text-aline:center;即可。如果想要居中的块级元素是内联元素(span,img,a等),直接在其⽗元素上添加text-align:center;即可。
.father{
width: 200px;
height: 200px;
background-color: aqua;
text-align: center;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
display: inline-block;
}
<div class="father">
<div class="son"></div>
</div>
2.使⽤margin:0 auto;⽔平居中
居中的元素必须是块级元素,如果是⾏内元素,需要添加display:block;⽽且元素不浮动。
.father{
width: 200px;
height: 200px;
background-color: aqua;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
margin: 0 auto;
}
<div class="father">
<div class="son"></div>
</div>
3.定位实现⽔平垂直居中(需要计算偏移值)必须要知道居中的元素的宽⾼
.father{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
position: absolute;
left: 50%;
top:50%;
margin-left: -50px;
margin-top:-50px;
}
<div class="father">
<div class="son"></div>
</div>
4.定位实现居中(不需计算偏移值)
margin:auto;和四个⽅向定位搭配使⽤,不需要知道元素的宽⾼
.father{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div class="father">
<div class="son"></div>
</div>
5.定位配合css3新属性transform:translate(x,y)使⽤
不需要知道元素的宽度和⾼度,在移动端⽤的⽐较多,因为移动端对css3新属性的兼容性⽐较好。
.father{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
div中的div居中}
.son{
width: 100px;
height: 100px;
background-color: brown;
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
<div class="father">
<div class="son"></div>
</div>
6.css3新属性calc()和定位配合使⽤(需要知道元素的宽⾼)
⽤于动态计算长度值。
需要注意的是,运算符前后都需要保留⼀个空格,例如:width: calc(100% - 10px);
任何长度值都可以使⽤calc()函数进⾏计算;
calc()函数⽀持 "+", "-", "*", "/" 运算;
calc()函数使⽤标准的数学运算优先级规则;
.father{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
<div class="father">
<div class="son"></div>
</div>
7.使⽤flex弹性盒布局实现⽔平垂直居中不需要知道元素本⾝的宽⾼以及元素的属性
.father{
width: 200px;
height: 200px;
background-color: aqua;
display: flex;
justify-content:center;
align-items:center;
}
.son{
width: 100px;
height: 100px;
background-color: brown;
}
<div class="father">
<div class="son"></div>
</div>