如何水平垂直居中?

1. 通过定位,给父盒子相对定位,子盒子绝对定位,top、left为50%,再margin-left : -(子盒子宽的一半)px; margin-top: -(子盒子高的一半)px;<style> div { position: relative; height: 400px; width: 400px; background-color: pink; } span { position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; display: block; width: 100px; height: 100px; background-color: purple; }</style>

2. 不依赖通过计算子盒子的宽高进行定位,可以用transform: translate 移动自身的一半就行了。<style> div { position: relative; height: 400px; width: 400px; background-color: pink; } span { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: block; width: 100px; height: 100px; background-color: purple; }</style>

3. 通过flex布局,设置垂直水平都居中。<style> div { display: flex; justify-content: center; align-items: center; height: 400px; width: 400px; background-color: pink; } span { display: block; width: 100px; height: 100px; background-color: purple; }</style>

发表评论