页面布局中,居中对齐是咱们常常遇到的场景,如今总结几个经常使用的方式供你们参考。css
html代码:html
<div class="btn">Hello World</div>
CSS代码:布局
.btn{ width: 120px; height: 48px; border: none; background: #f8f8f8; color: #333; /* 文本水平居中 */ text-align: center; /* 文本垂直居中 */ ling-height: 48px; }
效果如图所示:flex
HTML代码:3d
<div class="father"> <div class="son"></div> </div>
CSS代码:code
.father { width: 400px; height: 400px; margin: 0 auto; margin-top: 100px; background: lightblue; /*子元素定位能够是相对定位,也能够是绝对定位,因此父元素最好作定位限制。*/ position: relative; } .son { width: 100px; height: 100px; border: none; background: #1c3beb; /* 居中代码,定位能够是相对定位,也能够为绝对定位 */ position: relative; top: calc(50% - 50px); left: calc(50% - 50px); }
上面的子元素的偏移量计算,也能够由CSS3中的新属性transform来实现:orm
.son { width: 100px; height: 100px; border: none; background: #1c3beb; /* 居中代码,定位能够是相对定位,也能够为绝对定位 */ position: absolute; top: 50%; left: 50%; /*百分比是相对于自身宽高的偏移量计算*/ transform: translate(-50%, -50%); }
上面的子元素也能够利用绝对定位元素的流体特性和margin:auto的自动分配特性来实现居中:htm
.father { width: 400px; height: 400px; margin: 0 auto; margin-top: 100px; background: lightblue; position: relative; } .son { width: 100px; height: 100px; border: none; background: #1c3beb; /* 居中代码,定位为绝对定位 */ position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
.father { width: 400px; height: 400px; margin: 0 auto; margin-top: 100px; background: lightblue; /*启用弹性布局,主轴与交叉轴都采用居中对齐*/ display: flex; justify-content: center; align-items: center; } .son { width: 100px; height: 100px; border: none; background: #1c3beb; }
以上几种对齐效果都同样,可是考虑到兼容性等问题,推荐方式3。以上几种方式的对齐效果以下:blog