铭哥和佩佩的博客

铭哥和佩佩的博客分享Python、PHP、JavaScript、HTML5、CSS3等各种知识

CSS实现元素水平垂直居中

我们知道,实现元素的水平居中比较简单,在设置了宽度后,设置左右margin为auto就可以。 但是如何设置元素垂直居中呢? 当然,对于单行的文字,可以通过设置line-height来解决, 可以对于一个块状元素来说,就没有那么简单。下面我们总结了一些实现 元素垂直水平都对齐的几种方式。

一、定位+负边距

html部分

<body>
    <div class="box"></div>
</body>

css部分

.box{
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-150px;
    margin-top:-100px;
    padding:20px;
    width:300px;
    height:200px;
    background:#41D7FB;
}

特点

  • 兼容性较好,能够兼容到IE6
  • 元素的宽高需要固定
  • 比较经典的垂直居中实现方式

二、定位+自适应边距

html部分

<body>
    <div class="box"></div>
</body>

css部分

.box{
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin:auto;
    padding:20px;
    width:300px;
    height:200px;
    background:#41D7FB;
}

特点

  • 兼容IE8以及以上浏览器
  • 元素宽高不需固定,可以随内容适应

三、定位+CSS3位移

html部分

<body>
    <div class="box"></div>
</body>

css部分

.box{
    position:absolute;
    left:50%;
    top:50%;
    transform: translate(-50%, -50%);
    padding:20px;
    width:300px;
    height:200px;
    background:#41D7FB;
}

特点

  • 由于使用了CSS3中的transform属性,需要IE9+浏览器
  • 元素宽高不需固定,可以随内容适应

四、Flex布局实现

html部分

<body>
    <div class="box"></div>
</body>

css部分

html{
    display: flex;
    height: 100%;
    justify-content: center;
    align-items:center;
}
.box{
    padding:20px;
    width:300px;
    height:200px;
    background:#41D7FB;
}

特点

  • 简单直接
  • 兼容性较差,需要IE10+
  • 父元素高度需要指定
  • 元素的宽高可以随内容适应

五、table-cell配合inline-block

html部分

<body>
    <div class="table">
    <div class="table-row">
        <div class="table-cell">
        <div class="box"></div>
        </div>
    </div>
    </div>  
</body>

css部分

.table{
    display:table;
    width:100%;
    height:600px;
}
.table-row{
    display: table-row;
}
.table-cell{
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.box{
    display: inline-block;
    padding:20px;
    width:300px;
    height:200px;
    background:#41D7FB;
}

特点

  • 需IE8+兼容
  • 元素宽高可以随内容适应
  • 需设置较多的标签和css样式

实例代码

http://pan.baidu.com/s/1o8r51wQ

添加新评论