css水平垂直居中几种方法?
首先我们规定两个div,为父子级别,后面各个案例都是基于
1 <div class="parent"> 2 <div class="child"> 3 demo 4 </div> 5 </div>
一、最简单的居中 margin:0 auto,上代码
1 .parent { 2 width: 200px; 3 height: 200px; 4 background-color: crimson; 5 } 6 7 .child { 8 width: 100px; 9 height: 100px; 10 margin: 0 auto; 11 text-align: center; 12 line-height: 100px; 13 background-color: orange; 14 }
二、第二种也是利用margin属性设置left,top,需要设置父级position:relative;子级position:absolute;
1 .parent { 2 position: relative; 3 width: 200px; 4 height: 200px; 5 background-color: crimson; 6 } 7 8 .child { 9 position: absolute; 10 width: 100px; 11 height: 100px; 12 background-color: orange; 13 left: 50%; 14 top: 50%; 15 margin: -50px 0 0 -50px; 16 }
三、利用transform的平移方法translate,同样要设置position
1 .parent { 2 position: relative; 3 width: 200px; 4 height: 200px; 5 background-color: crimson; 6 } 7 8 .child { 9 position: absolute; 10 width: 110px; 11 height: 110px; 12 background-color: orange; 13 left: 50%; 14 top: 50%; 15 transform: translate(-50%, -50%); 16 }
四、利用flex布局,设置父级justify-content和align-items,或者设置父级的justify-content和子级align-self属性都可以达到效果
1 .parent { 2 width: 200px; 3 height: 200px; 4 background-color: crimson; 5 display: flex; 6 justify-content: center; 7 align-items: center; 8 } 9 10 .child { 11 width: 100px; 12 height: 100px; 13 background-color: orange; 14 }
or
1 .parent { 2 width: 200px; 3 height: 200px; 4 background-color: crimson; 5 display: flex; 6 justify-content: center; 7 } 8 9 .child { 10 width: 100px; 11 height: 100px; 12 background-color: orange; 13 align-self: center; 14 }
五、利用left,top,bottom,right设置相等的值,不一定为0,加上margin:0
1 .parent { 2 position: relative; 3 width: 200px; 4 height: 200px; 5 background-color: crimson; 6 } 7 8 .child { 9 position: absolute; 10 width: 100px; 11 height: 100px; 12 background-color: orange; 13 left: 0; 14 right: 0; 15 top: 0; 16 bottom: 0; 17 margin: auto; 18 }
六、利用inline-block的vertical-align:middle去对齐伪元素
1 .parent { 2 width: 200px; 3 height: 200px; 4 background-color: crimson; 5 text-align: center; 6 overflow: auto; 7 } 8 9 .parent::after { 10 content: ''; 11 display: inline-block; 12 vertical-align: middle; 13 height: 100%; 14 margin-left: -0.25em; 15 } 16 17 .child { 18 width: 100px; 19 height: 100px; 20 background-color: orange; 21 display: inline-block; 22 vertical-align: middle; 23 }
待完善