如下将整理关于使用CSS使元素居中的一些方法浏览器
案例模版:bash
<body>
<div id="main">
<div id="center">这个块居中</div>
</div>
</body>
<style>
body{
height: 200px;
}
#main{
border:1px red solid;
}
#center{
border: 1px green solid;
}
</style>
复制代码
#center{
width: 100px;
margin: 0 auto;
}
复制代码
要让居中元素知足两个条件:其一,元素须要有一个固定宽度值;其二元素的margin-left和margin-right都必须设置为auto,这两个条件少了任何一个都没法让元素达到水平居中的效果。flex
缺点:须要固定居中元素的宽度。spa
注意:当元素处于position:absolute;时,margin:0 auto无效,须要将right于left都设为0才能够,以下所示:3d
#center{
width: 100px;
margin: 0 auto;
position:absolute;
right:0;
left:0;
}
复制代码
#center{
width: 100px;
position: absolute;
left: 50%;
margin-left: -100px; /*值为width的一半*/
}
复制代码
居中元素设置一个负的“margin-left”而且值等于宽度的一半,另外若是元素不是相对于浏览器的话,还须要在其父元素上设置一个相对定位“position: relative”。code
缺点:须要固定居中元素的宽度。orm
以上两种方式都必须设置固定的宽度值,下面将解决不须要固定宽度值的方法。cdn
#main{
text-align: center;
}
复制代码
对居中元素的父元素设置text-align属性。blog
优势:不须要设置元素的固定宽度。string
缺点:居中元素必须是inline或者设置为inline-block。
#main{
display: inline-block;
position: relative;
left: 50%;
}
#center{
display: inline-block;
position: relative;
right: 50%;
}
复制代码
一、将#main与#center所有设置为inline-block,将包裹他们的内容:
二、将#main往右移其宽度的50%:
三、而后将#center往左移其宽度的50%:
四、最终#center元素居中。
优势:不须要设置元素的固定宽度。
缺点:居中元素的元素被设置为inline-block。
#main{
position: relative;
}
#center{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
复制代码
首先left:50%先右移#main50%的宽度,而后经过translateX(-50%)在左移自己50%的宽度。
优势:不须要设置元素的固定宽度。
缺点:居中元素被设置为absolute。
#main{
display: flex;
justify-content: center;
}
复制代码
优势:不须要设置元素的固定宽度。
缺点:父元素被设置为flex。
#main{
height: 200px;
line-height: 200px;
}
复制代码
居中元素的父元素必需要设置准确height数值。而且居中元素若是是多行文本将错乱。这种方式适合小元素,单行文本。
缺点:须要固定父元素的height值,而且居中元素若是是多行文本将错乱。仅适合小元素,单行文本。
#main{
position: relative;
}
#center{
height: 50px;
position: absolute;
top: 50%;
margin-top: -25px; /*值为height的一半*/
}
或
#center{
height: 50px;
position: absolute;
top: calc(50% - 25px);
}
复制代码
缺点:须要固定居中元素的height值。
以上两种方式都必须设置固定的height值,下面将解决不须要固定heignt值的方法。
#main{
height: 100%;
display: table;
}
#center{
display: table-cell;
vertical-align: middle;
}
复制代码
父元素设置为display:table;子元素设置为display:table-cell;而且设置vertical-align:midden;
<body>
<div id="main">
<div id="center">这个块居中</div>
<div id="other"></div>
</div>
</body>
<style>
#main{
height: 100%;
}
#center,#other{
display: inline-block;
vertical-align: middle;
}
#other{
height: 100%;
}
</style>
复制代码
为同一行的inline-block元素设置vertical-align:middle,该行内的inline-block元素会按照元素的垂直中心线对齐。
缺点:须要额外添加一个元素。
#main{
height:100%;
position: relative;
}
#center{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
复制代码
首先top:50%先下移#main50%的高度,而后经过translateY(-50%)在上移自己50%的高度。
优势:不须要设置元素的固定高度。
缺点:居中元素被设置为absolute。
下移到#main50%的高度还有另外的方式
#center{
margin:50% auto 0; //下移到#main50%的高度
transform: translateY(-50%);
}
或
#center{
margin:50vh auto 0; //下移到视口50%的高度
transform: translateY(-50%);
}
复制代码
#main{
height:100%;
display: flex;
align-items: center;
}
复制代码
优势:不须要设置元素的固定宽度。
缺点:父元素被设置为flex。