在html学习或网页开发中,会遇到需要设置水平居中的场景,但不同类型的元素水平/垂直居中有不同书写格式或者代码,现在我来盘点一下:
(a):text-align: center; (注:通常给父元素添加该语法)
/* div为span的父元素 */
div {
text-align: center;
width: 500px;
height: 500px;
background-color: pink;
}
<div><span>123span>div>
(b): 用flex弹性布局:父元素: display: flex; flex-direction: column; 子元素: align-self: center;
div {
display: flex;
width: 500px;
height: 500px;
background-color: pink;
flex-direction: column;
}
span {
align-self: center;
}
<div><span>123span>div> >
(c):将行内元素转换为块级元素设置宽高,再利用margin:0 auto;(和下面一致,都可以互相转换)
div {
width: 500px;
height: 500px;
background-color: pink;
}
span {
display: block;
width: 50px;
height: 50px;
margin: 0 auto;
}
(d):父元素:position: relative;
子元素: position: absolute;
left: 50%;
transform: translateX(-50%);
div {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
span {
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
}
(a):line-height: 100px;(注:行高和父盒子高度一致,比如父元素高为100px,此处就该为100px)
div {
width: 500px;
height: 500px;
background-color: pink;
}
span {
width: 50px;
height: 50px;
line-height: 500px;
}
(b):利用3D,position: absolute;
top: 50%;
transform:translateY(50%)
div {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
span {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
}
(a):margin: 0 auto; (设置高宽,最常用)
div {
width: 500px;
height: 500px;
background-color: pink;
}
div div {
width: 100px;
height: 100px;
background-color: skyblue;
margin: 0 auto;
}
(b):用flex弹性布局:父元素:display: flex;
flex-direction: column;
子元素:align-self: center;
div {
display: flex;
width: 500px;
height: 500px;
background-color: pink;
flex-direction: column;
}
div div {
align-self: center;
width: 100px;
height: 100px;
background-color: skyblue;
}
(c):
利用父相子绝,父元素:position: relative;
子元素: position: absolute;
left: 50%;
margin-left: -50%;
div {
width: 500px;
height: 500px;
background-color: pink;
}
div div {
width: 100px;
height: 100px;
background-color: skyblue;
margin: 0 auto;
}
(d):
父元素:position: relative;
子元素: position: absolute;
left: 50%;
transform: translateX(-50%);
div {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
span {
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
}
(a):父元素:position: relative;
子元素: position: absolute;
top: 50%;
transform: translateY(-50%);
div {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
div {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
}
(b):父元素: display: table-cell;
vertical-align: middle;
text-align: center;
div {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 500px;
height: 500px;
background-color: pink;
}
div div {
width: 100px;
height: 100px;
background-color: skyblue;
}
总结:行内元素和块元素可以相互转换,因此方法千万种,对一种熟练应用即可
作者:刘港辉
本文源自:《 普歌-赤道团队:文本,图片,行内块元素/块级元素水平/垂直居中合集(内容较多,建议收藏)》
本文版权归作者所有,欢迎转载。
如果有不足,欢迎雅正留言