CSS居中布局汇总
CSS 居中方案 📏
元素水平居中
- 将行内元素包裹在一个属性
display为block的父元素中, 父元素中添加
1 .box { 2 text-align: center; 3 }
- 块状元素解决方案
需要为父元素设定宽高
1 .box { 2 width: 200px; 3 margin: 0 auto; 4 }
元素水平垂直居中
🌰position元素已知宽度, 绝对定位+margin反向偏移(transform`)
1 .wrap { 2 position: relative; 3 background-color: orange; 4 width: 300px; 5 height: 300px; 6 } 7 .example2 { 8 background-color: red; 9 width: 100px; 10 height: 100px; 11 position: absolute; 12 left: 50%; 13 top: 50%; 14 margin: -50px 0 0 -50px; 15 /* 第二种: 将margin换成transform, 如下 */ 16 /* transform: translate(-50%, -50%); */ 17 }
🌰flex布局
1 .wrap { 2 background-color: #ff8c00; 3 width: 200px; 4 height: 200px; 5 display: flex; 6 justify-content: center; /* 使子项目水平居中 */ 7 align-items: center; /* 使子项目垂直居中 */ 8 } 9 .example3 { 10 background-color: #f00; 11 width: 100px; 12 height: 100px; 13 }
还可以使用table-cell布局, 但是因为该布局对于资源的消耗过大, 现在基本没有使用, 不必了解
🌰 绝对布局
1 <div class="wrap"> 2 <div class="example3"> 3 居中显示 4 </div> 5 </div> 6 .wrap { 7 position: relative; 8 background-color: orange; 9 width: 200px; 10 height: 200px; 11 } 12 .example3 { 13 position: absolute; 14 top: 0; 15 left: 0; 16 right: 0; 17 bottom: 0; 18 background-color: red; 19 width: 100px; 20 height: 100px; 21 margin: auto; 22 }
🌰 给子元素相对定位, 在通过translateY()得到垂直居中
1 .wrap { 2 position: relative; 3 background-color: orange; 4 width: 200px; 5 height: 200px; 6 } 7 .example3 { 8 position: absolute; 9 top: 50%; 10 transform: translateY(-50%); 11 background-color: red; 12 width: 100px; 13 height: 100px; 14 margin: 0 auto; 15 }
🌰 利用inline-block的vertical-align: middle去对齐after伪元素
居中块的尺寸可以做包裹性、自适应内容,兼容性也相当好。缺点是水平居中需要考虑inline-block间隔中的留白(代码换行符遗留问题)
1 .wrap { 2 text-align: center; 3 overflow: auto; 4 width: 200px; 5 height: 200px; 6 background-color: orange; 7 } 8 .example3 { 9 display: inline-block; 10 background-color: red; 11 vertical-align: middle; 12 width: 100px; 13 height: 100px; 14 } 15 .wrap:after { 16 content: ''; 17 display: inline-block; 18 vertical-align: middle; 19 height: 100%; 20 margin-left: -0.25em; 21 /* To offset spacing. May vary by font */ 22 }
🌰display: flex-box
能解决各种排列布局问题
1 .wrap { 2 display: -webkit-flex; 3 display: -moz-box; 4 display: -ms-flexbox; 5 display: -webkit-box; 6 display: flex; 7 -webkit-box-align: center; 8 -moz-box-align: center; 9 -ms-flex-align: center; 10 -webkit-align-items: center; 11 align-items: center; 12 -webkit-box-pack: center; 13 -moz-box-pack: center; 14 -ms-flex-pack: center; 15 -webkit-justify-content: center; 16 justify-content: center; 17 width: 200px; 18 height: 200px; 19 background-color: orange; 20 } 21 .example3 { 22 width: 100px; 23 height: 100px; 24 background-color: red; 25 }

浙公网安备 33010602011771号