首页 > 技术文章 > css完全居中

djlxs 2016-08-01 17:56 原文

    关于css完全居中的文章,网上已经很多了。这里主要记录一下思路,方便记忆,最后附上所有的参考链接。

   1  水平居中

    1  内部是内联元素,那么我们直接可以在父元素上面设置,text-align:center。

    2 有多个内联元素,排成一排,实现水平居中。

    html代码:

<div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>

 

css代码:

 

.container {
  width: 800px;
  height: 200px;
  border: 3px solid #e5e5e5;
  text-align:center;
  font-size:0;   //避免子元素设置成display:inline-block时,产生几像素的间隙

}

  .container div {
    font-size:16px; //恢复,div里面的字体大小为0.
    width: 100px;
    height: 50px;
    border: 1px solid red;
    display: inline-block; }

那么这里就实现了,几个内联元素同排居中的效果。

当然我们也可以用flex布局来实现,只需要在父容器中添加两行代码

display: flex;
justify-content: center;

至于flex布局,大家可以看看这篇文章

http://www.ruanyifeng.com/blog/2015/07/flex-examples.html

  3 第三种就是如果里面是跨级元素 那么我们一般最常用的就是 

margin-left: auto;
margin-right: auto;

垂直居中

1 块级元素里面的内联元素,如果只有单行,我们设置line-height的值等于父元素的高度,缺点就是只能用在单行上面。

2 块级元素里面的块级元素居中  如果知道子元素的宽高,那么我们用负的margin来实现,因为所有浏览亲都支持,这个属性。

<div class="container">
    <div class="cneter2">知道宽高</div>    
</div>
.container{
            width:800px;
            height:200px;
            border:3px solid #e5e5e5;
            position: relative;
        }

.container div {
    width: 100px;
    height: 50px;
}

.cneter2{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;  //这个值为子元素宽度的一半
    margin-top: -25px    //这个值为子元素高度的一半
}

 

当然你也可以利用calc属性,减少两个属性,当然是否支持,也是你需要考虑的,还有"-"左右两边一定要有一个空格。

.cneter2{
    position: absolute;;
    top: calc(50% - 25px);
    left: calc(50% - 50px);
    
}

 还有一种方式如下也是要知道具体宽高

.center2{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 50px;
    height: 50px;
    background: red;
}

 

在不知道子元素具体宽高的情况下

.center1{
    position: absolute;
    top: 50%;
    left: 50%;
    background: yellow;
    transform: translate(-50%,-50%);
}

 上面这种方式在知道宽高的情况下,当然也能用,只不过用margin的话,不用担心浏览器不支持的问题。

 

好了就写这么多,主要是明白思路和在哪种情况下使用哪种方式会好一些。

最后附上一些链接:http://www.w3cplus.com/css/centering-css-complete-guide.html

英文原文:https://css-tricks.com/centering-css-complete-guide/

推荐阅读