美文网首页
css垂直水平居中

css垂直水平居中

作者: cooqi | 来源:发表于2017-04-07 23:43 被阅读0次

垂直居中一直是比较常用的布局,但经常会不知道该怎么办
网上各种方法都有,如何找一种适用于当前项目的很重要

文字居中和已知具体宽高的元素 如何垂直居中就不说了

个人觉得没有什么居中是这三种方法解决不了的

方法1:table-cell

.test{
 display:table;
}
.test div{
    display: table-cell;
    vertical-align: middle;
    text-align: center;        
}

方法2:绝对定位(适合定位的条件下推荐)

.test2{position:relative}
.test2 div{
  width: 50%; 
  height: 50%; 
  background: #000;
  overflow: auto; 
  margin: auto; 
  position: absolute; 
  top: 0; left: 0; bottom: 0; right: 0; 
}

方法3:display:flex(不考虑ie兼容下推荐)

.test3{  /*让内部元素垂直水平居中,适用于文本*/
    display: flex;
    justify-content:center;
    align-items:Center;
}
<div class="test3">123</div>
.main{width: 1000px;height: 1000px;background: #000;display: flex;}
.testCenter{margin:auto;padding: 20px;background: red;color: #fff}
/*让子元素居中,子元素宽高不固定*/
<div class="main">
    <div class="testCenter">center</div>
</div>

原理什么的,可以百度

这里记一个额外情况
当父级元素的宽度小于子元素的时候,怎么让子元素水平居中

TIM截图20180525084335.png

比较常见于二级导航 和 已有宽度的通栏广告
这种情况就得用另一种了

left: 50%;
transform: translateX(-50%);

相关文章

网友评论

      本文标题:css垂直水平居中

      本文链接:https://www.haomeiwen.com/subject/bavkattx.html