元素垂直居中方法

来源:互联网 发布:检测电源的软件 编辑:程序博客网 时间:2024/04/28 09:52

1、固定height的元素居中


(1) 使用绝对定位(兼容所有浏览器,浏览器窗口缩小时,部分内容会消失)

<div class="content">居中元素</div>.content {    position: absolute;    top: 50%;    left: 50%;    width: 600px;    height: 600px;    margin: -300px 0 0 -300px;    background-color: silver;}

(2) 在居中元素外插入一个div(兼容所有浏览器,浏览器窗口缩小时,内容不会消失)

<div class="main"></div><div class="content">居中元素</div>.main {    float: left;    height: 50%;    margin-bottom: -300px;}.content {    clear: both;    width: 600px;    height: 600px;    position: relative;    background-color: silver;}

(3) 使用绝对定位,margin:auto(兼容所有浏览器,浏览器窗口缩小时,部分内容会消失)

<div class="content">居中元素</div>.content {    position: absolute;    top: 0;    bottom: 0;    left: 0;    right: 0;    width: 600px;    height: 600px;    margin: auto;    background-color: silver;}

2、不固定height的元素居中

(1) 使用display:table(兼容所有浏览器)

<div id="wrapper"><div id="cell"><div class="content">居中元素</div></div></div>#wrapper {    display: table;    width: 50%;    height: 100%;    margin: 0 auto;}#cell {    display: table-cell;    vertical-align: middle;}.content {    background-color: silver;}

(2) 使用translate(不兼容ie8,浏览器窗口缩小时,部分内容会消失) 

<div class="content">居中元素</div>.content {    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);    background-color: silver;}

0 0