在实际应用中很多地方不仅要求实现元素的水平居中或者垂直居中效果,还可能会在水平方向和垂直方向上都要实现居中效果,下面就简单介绍几种元素水平垂直居中的方法(注:不同的方法会存在一些优缺点以及兼容性问题)
hmtl结构:
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
- 定位 + 负外边距
.parent{
position: relative;
width: 200px;
height: 200px;
background-color: blue;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
margin-left: -25px;
margin-top: -25px;
background-color: #fff;
}
原理:元素设置定位并给定 50% 的top值和left值,再通过 负margin 将元素向左上移动自身宽高的一半(margin-top:-height/2; margin-left:-width/2),该方法前提是要知道元素的宽高
- 定位 + 平移
.parent{
position: relative;
width: 200px;
height: 200px;
background-color: green;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 50px;
height: 50px;
background-color: #fff;
}
原理:和上面方法类似,不同的是使用CSS3新增属性 transform 中的 translate 平移属性代替 margin属性,这样就是根据自身尺寸进行移动,缺点是由于为新增属性,兼容性自然就不是很好,远古IE不支持。
- 强大的 “margin:auto”
.parent {
position: relative;
width: 200px;
height: 200px;
background-color: deeppink;
}
.child {
position: absolute;
top: 0;
bottom:0;
left: 0;
right: 0;
width: 50px;
height: 50px;
margin: auto;
background-color: #fff;
}
原理:该方法的关键点是:1.绝对定位的(top、right、bottom、left)四个属性均要设置值为0;2.margin:auto,能够适用单个元素或者父子级元素,设置绝对定位并添加 margin:auto 属性就能够实现水平垂直居中,元素可自定义宽高,也可不设置(需要是自身存在尺寸的元素:img等),具体 绝对定位+margin:auto 的实现原理参考https://www.zhangxinxu.com/wordpress/2013/11/margin-auto-absolute-%E7%BB%9D%E5%AF%B9%E5%AE%9A%E4%BD%8D-%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD/
- flex布局
div.parent{
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: red;
}
div.child{
width: 50px;
height: 50px;
background-color: lime;
}
//或者
div.parent{
display: flex;
width: 200px;
height: 200px;
background-color: red;
}
div.child{
width: 50px;
height: 50px;
margin:auto;
background-color: lime;
原理:通过给父元素设置display为flex,再设置 item 的主轴和辅轴的对齐方式,兼容性也不是很好(IE8+ 及大众浏览器),大多数用于移动端布局
- grid布局
.parent{
display: grid;
width: 200px;
height: 200px;
background-color:deepskyblue;
}
.child{
justify-self: center;
align-self: center;
width: 50px;
height: 50px;
background-color: #fff;
}
原理:和flex布局实现思路类似。
- 表格布局
.parent {
display: table-cell;
height: 200px;
width: 200px;
background-color: orange;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
width: 100px;
height: 100px;
background-color: blue;
}
以上内容参考自其它文章并结合自身理解,若存在错误请指出,谢谢!!!
