网页制作 发布日期:2024/12/25 浏览次数:1
直奔主题在这里提供三种块级元素垂直水平居中的方法
flex
html
<div class="parent"> <div class="child"></div> </div>
css
.parent{ width: 500px; height: 500px; margin: 0 auto; border: 1px solid gainsboro; display: flex; justify-content: center; align-items: center; } .child{ width: 200px; height: 200px; background: red; }
定位+margin
html
<div class="parent"> <div class="child"></div> </div>
css
.parent{ position: relative; width: 500px; height: 500px; margin: 0 auto; border: 1px solid gainsboro; } .child{ position: absolute; top: 50%; left: 50%; width: 200px; height: 200px; margin-left: -100px; margin-top: -100px; background: red; }
定位+transform
html
<div class="parent"> <div class="child"> <span>我是子元素</span> </div> </div>
css
.parent{ position: relative; width: 500px; height: 500px; margin: 0 auto; border: 1px solid gainsboro; } .child{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background: red; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。