css盒子居中

看到标题,相信大家并不陌生。这个问题,经常会出现在面试题中。通常会要求面试者写出几种方法。那么,究竟有几种方法,每种方法的兼容情况如何,相信大家很少研究过。今天,我们就一起来看看。

通常分为2种情况,已知元素的宽度或未知。

我们先说说在已知的情况下,要如何设置。

举例说明:有2个元素,让子元素相对于父元素水平垂直居中。

html代码:

 
  1. <div class="box">

  2. <div class="innerbox">css设置元素水平垂直居中显示</div>

  3. </div>

1、利用定位及设置元素margin值为自身的一半。

css代码:

 
  1. .box{

  2. width: 400px;

  3. height: 200px;

  4. border: 5px solid #ddd;

  5. margin: 50px auto;

  6. position: relative;

  7. }

  8. .innerbox{

  9. width: 300px;

  10. height: 100px;

  11. border: 5px solid #f00;

  12. font-size: 16px;

  13. position: absolute;

  14. left: 50%;

  15. top: 50%;

  16. margin: -50px 0 0 -150px;

  17. }


说明:此方法,在我们工作中经常用到,兼容性好。demo

2、margin:auto

css代码:

 
  1. .box{

  2. width: 400px;

  3. height: 200px;

  4. border: 5px solid #ddd;

  5. margin: 50px auto;

  6. position: relative;

  7. }

  8. .innerbox{

  9. position: absolute;

  10. left: 0;

  11. top: 0;

  12. right: 0;

  13. bottom: 0;

  14. width: 300px;

  15. height: 100px;

  16. margin: auto;

  17. border: 5px solid #f00;

  18. }

说明: position: absolute; left: 0; right: 0; top: 0; bottom: 0;这是自动填充父元素的可用空间。然而给子元素设定了宽高,那么多余的空间,会被margin:auto平均分配。

查看demo

跟已知元素宽高相比,实现未知元素宽高水平垂直居中显示的方法较多。

1、利用css3属性transform实现。

css代码:

 
  1. .box{

  2. width: 400px;

  3. height: 200px;

  4. border: 5px solid #ddd;

  5. margin: 50px auto;

  6. position: relative;

  7. }

  8. .innerbox{

  9. position: absolute;

  10. left: 50%;

  11. top: 50%;

  12. border: 5px solid #f00;

  13. transform: translate(-50%,-50%);

  14. }


说明:这种方法在移动端被广泛使用。但是,只支持高版本浏览器(IE9+以上的浏览器支持)。demo


2、将父元素设置成display: table, 子元素设置为单元格 display: table-cell。这个方法跟上面介绍的方法不同,它不是让元素居中,而是让元素包含的内容居中。

css代码:

 
  1. .box{

  2. width: 400px;

  3. height: 200px;

  4. border: 5px solid #ddd;

  5. margin: 50px auto;

  6. display: table;

  7. }

  8. .innerbox{

  9. display: table-cell;

  10. vertical-align: middle;

  11. text-align: center;

  12. border: 5px solid #f00;

  13. }


说明:利用表格的特性,将子元素看成行内元素,实现元素中的文字(文字可以是单行的,也可以是多行的)或图片水平垂直居中。demo


3、css3新的布局方法,弹性布局 display: flex。这个方法,在已知或未知元素宽高的情况下,都能使元素居中显示。

css代码:

 
  1. .box{

  2. width: 400px;

  3. height: 200px;

  4. border: 5px solid #ddd;

  5. margin: 50px auto;

  6. display: flex;

  7. align-items: center;

  8. justify-content: center;

  9. }

  10. .innerbox{

  11. width: 300px; /*宽度可以省略*/

  12. height: 100px; /*高度可以省略*/

  13. border: 5px solid #f00;

  14. font-size: 16px;

  15. }

说明: 此方法只支持IE9+以上的浏览器。display: flex代表弹性布局,align-items: center 代表垂直方向上的居中,justify-content: center代表水平方向上的居中。这些是css3中的新属性,感兴趣的同学可以查找相关资料学习。这里不多介绍。

转自https://blog.csdn.net/yhbsww0523/article/details/78642043

猜你喜欢

转载自blog.csdn.net/hailangtuteng/article/details/82628602