本文以<div>元素为例
本文转载
1.已知块级元素的宽和高,使用绝对定位absolute和外边距实现水平垂直居中。
父元素position:relative,子元素position:absolute;top:50%;left:50%;margin-top:-height/2;margin-left:-width/2;
(思想:先把块级元素中的左上角定位到父元素的中心,然后再向上向左偏移本身的一半,就达到了是本身的中心居中的目的)
效果图如下:
代码:
1 <div class="box"> 2 <div class="center-box1"> 3 <p>【第一种方法】知道长和宽,使用绝对定位+外边距设定水平垂直居中</p> 4 </div> 5 </div> 6 7 .box { 8 background: #6c94be; 9 100%; 10 height: 450px; 11 position: relative; 12 } 13 .center-box1 { 14 position: absolute; 15 top: 50%; 16 left: 50%; 17 margin-top: -100px; 18 margin-left: -100px; 19 200px; 20 height: 200px; 21 background: #5B83AD; 22 }
2.使用css3 display:flex(IE存在兼容性问题)
父元素样式属性display:flex;子元素使用margin:auto。这种方式在子块级元素宽高不确定的时候(宽高会自适应为其里面内容的宽高)依然可以使用。
效果图如下:
代码:
1 <div class="box"> 2 <div class="center-box2"> 3 <p>【第二种方法】使用css3样式属性display:flex设定水平垂直居中</p> 4 </div> 5 </div> 6 7 .box { 8 background: #6c94be; 9 100%; 10 height: 450px; 11 display: flex; 12 } 13 .center-box2 { 14 margin: auto; 15 200px; 16 background: #5B83AD; 17 }
3.使用绝对定位+CSS3 transform(由于transform中translate偏移的百分比都是相对于自身而言的,所以不像方法一种那样必须知道子元素的宽高才行,但是对于IE只有IE9+才支持)
效果图如下:
代码:
1 <div class="box"> 2 <div class="center-box3"> 3 <p>【第三种方法】使用css3样式属性transform,transform中translate偏移的百分比值是相对于自身大小的</p> 4 </div> 5 </div> 6 7 .box { 8 background: #6c94be; 9 100%; 10 height: 450px; 11 position: relative; 12 } 13 14 .center-box3 { 15 position: absolute; 16 top: 50%; 17 left: 50%; 18 transform: translate(-50%,-50%); 19 background: #5B83AD; 20 200px; 21 }
4.已知子元素的宽和高,设置其样式属性position:absolute;top:0;left:0;bottom:0;right:0;margin:auto;
效果图如下:
代码:
1 <div class="box"> 2 <div class="center-box4"> 3 <p>【第四种方法】已知宽和高,绝对定位+margin:auto;</p> 4 </div> 5 </div> 6 7 .box { 8 background: #6c94be; 9 100%; 10 height: 450px; 11 position: relative; 12 } 13 .center-box4 { 14 position: absolute; 15 top: 0; 16 left: 0; 17 bottom: 0; 18 right: 0; 19 200px; 20 height: 200px; 21 background: #5B83AD; 22 margin: auto; 23 }