CSS居中对齐

您所在的位置:网站首页 div居中对齐的css代码 CSS居中对齐

CSS居中对齐

#CSS居中对齐| 来源: 网络整理| 查看: 265

CSS实现居中对齐的几种方式

页面布局中,居中对齐是咱们常常遇到的场景,如今总结几个经常使用的方式供你们参考。css

场景一:按钮文字居中对齐,line-height + text-align

html代码:html

Hello World

CSS代码:布局

.btn{ width: 120px; height: 48px; border: none; background: #f8f8f8; color: #333; /* 文本水平居中 */ text-align: center; /* 文本垂直居中 */ ling-height: 48px; }

效果如图所示:flex

场景二:父元素内部的子元素居中对齐,子元素设置position定位来实现 方式1:position+top/left定位实现

HTML代码:3d

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); } 方式2:position+top/left+transform来实现居中

上面的子元素的偏移量计算,也能够由CSS3中的新属性transform来实现:orm

.son { width: 100px; height: 100px; border: none; background: #1c3beb; /* 居中代码,定位能够是相对定位,也能够为绝对定位 */ position: absolute; top: 50%; left: 50%; /*百分比是相对于自身宽高的偏移量计算*/ transform: translate(-50%, -50%); } 方式3:position+margin来实现居中

上面的子元素也能够利用绝对定位元素的流体特性和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; } 方式4:弹性布局实现居中 .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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3