使用CSS实现元素居中在实际应用中非常常见,下边我说一下我所总结的几个实现元素居中的方法。
html基本代码
<div class="father">
<div class="child"></div>
</div>
css基本代码
* {
margin: 0;
padding: 0;
}
.father {
width: 100%;
height: 600px;
background-color: #8d8d8d;
}
方法一
使用position: absolute 和 transform实现居中,此时父级应有position: relative属性
.child {
width: 300px;
height: 300px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方法二
使用position: absolute 和 margin、left、right实现居中,此时父级应有position: relative属性
.child {
width: 300px;
height: 300px;
background: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
方法三
设置上下左右都为0,并使用margin auto实现居中,此时父级应有position: relative属性
.child {
width: 300px;
height: 300px;
background: red;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
方法四
通过relative和margin auto实现,此时父级需要设置overflow:hidden(将父级设置为BFC)
.child {
position: relative;
width: 300px;
height: 300px;
margin: 150px auto;
background: red;
}
方法五
使用display: flex,align-items: center,justify-content: center
.father {
display: flex;
align-items: center;
justify-content: center;
}
.child {
width: 300px;
height: 300px;
background: red;
}
方法六
使用display: flex,margin: auto
.father {
display: flex;
}
.child {
margin: auto;
width: 300px;
height: 300px;
background: red;
}
方法七
元素内部字体实现居中方法
<div class="father">
<div class="child">
<p>hello</p>
</div>
</div>
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background: red;
}
方法八
使用calc函数,其中的“-”两边必须加上空格,相减数为当前元素宽高
.child {
position: absolute;
width: 300px;
height: 300px;
left: calc(("当前屏幕像素" - 300px)/2);
top: calc((600px - 300px)/2);
background: red;
}
本人才疏学浅,如有不对之处,烦请指正,如果各位有其他方法,烦请在评论区多多交流。