css元素居中方法总结
css实现元素居中。
1、使用position:absolute,设置left、top、margin-left、margin-top的属性
.one{
position:absolute;
width:200px;
height:200px;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
background:red;
}
这种方法基本浏览器都能够兼容,不足之处就是需要固定宽高。
2、使用position:fixed,同样设置left、top、margin-left、margin-top的属性
.two{
position:fixed;
width:180px;
height:180px;
top:50%;
left:50%;
margin-top:-90px;
margin-left:-90px;
background:orange;
}
大家都知道的position:fixed,IE是不支持这个属性的
3、利用position:fixed属性,margin:auto这个必须不要忘记了。
.three{
position:fixed;
width:160px;
height:160px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:pink;
}
4、利用position:absolute属性,设置top/bottom/right/left
.four{
position:absolute;
width:140px;
height:140px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:black;
}
5、利用display:table-cell属性使内容垂直居中
.five{
display:table-cell;
vertical-align:middle;
text-align:center;
width:120px;
height:120px;
background:purple;
}
6、最简单的一种使行内元素居中的方法,使用line-height属性
.six{
width:100px;
height:100px;
line-height:100px;
text-align:center;
background:gray;
}
这种方法也很实用,比如使文字垂直居中对齐。这种方法对于在盒子内部垂直居中是非常有效果的,但对于在整个body中居中不适用
7、使用css3的display:-webkit-box属性,再设置-webkit-box-pack:center/-webkit-box-align:center
.seven{
width:90px;
height:90px;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
background:yellow;
color:black;
}
8、使用css3的新属性transform:translate(x,y)属性
.eight{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-ms-transform:translate(-50%,-50%);
background:green;
}
这个方法可以不需要设定固定的宽高,需要使用绝对定位在移动端用的会比较多,在移动端css3兼容的比较好
9、最高大上的一种,使用:before元素
.nine{
position:fixed;
display:block;
top:0;
right:0;
bottom:0;
left:0;
text-align:center;
background:rgba(0,0,0,.5);
}
.nine:before{
content:'';
display:inline-block;
vertical-align:middle;
height:100%;
}
.nine .content{
display:inline-block;
vertical-align:middle;
width:60px;
height:60px;
line-height:60px;
color:red;
background:yellow;
}
10、css3还有一种left:50%;top:50%;transform:translate(-50%,-50%);
这种方法非常实用。而且如果不需要左右居中,那么translate里面也就只写一种即可。
11、还有一种是布局方面的居中,如果有3个元素在一排,让其3个在页面水平居中,3个元素之间的间距相等
使用方法是采用伪元素,然后使用弹性布局实现 总结:
水平居中
子元素为行内元素还是块状元素,宽度一定还是宽度未定,采取的布局方案不同。下面进行分析: 行内元素:对父元素设置text-align:center; 定宽块状元素: 设置左右margin值为auto; 不定宽块状元素: 设置子元素为display:inline,然后在父元素上设置text-align:center; 通用方案: flex布局,对父元素设置display:flex;justify-content:center;
垂直居中
垂直居中对于子元素是单行内联文本、多行内联文本以及块状元素采用的方案是不同的。 父元素一定,子元素为单行内联文本:设置父元素的height等于行高line-height 父元素一定,子元素为多行内联文本:设置父元素的display:table-cell或inline-block,再设置vertical-align:middle; 块状元素:设置子元素position:fixed(absolute),然后设置margin:auto; 通用方案: flex布局,给父元素设置{display:flex; align-items:center;}。
水平对齐:
两个并排元素都为inline或inline-block元素,然后设置左边元素vertival-align:middle即可