关于如何居中元素的总结

1.文本的居中  
height+line-height:配合使用,垂直方向居中 
text-align:父级的text-align,水平居中 
ps:text-align:center 只是将子元素里的内联元素居中。
还有一种文本居中的方式是定高父级元素激活表格属性和基线样式: 
display:table-cell;vertical-align:middle; / IE8,Firefox,chrome /
那么不是内联元素是如何实现居中的?margin: 0 auto;

2.定宽块元素的水平居中 
两个条件:宽度固定值+块级元素
.wrap{width: 200 px;border: 1 px solid red;margin: 0 auto;} //宽度必须给值 <div class= "wrap" ></div>

3.块元素的垂直水平居中

固定宽的块元素

.wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE;position:relative;} .box{width: 100 px;height: 100 px;background:red;position:absolute;top: 50 %;left: 50 %;margin-top:- 50 px;margin-left:- 50 px;}< div class= "wrap" > < div class= "box" ></ div ></ div >

.wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE;position:relative;} .box{width: 100 px;height: 100 px;background:red;position:absolute;left: 0 ;top: 0 ;right: 0 ;bottom: 0 ;margin:auto;}< div class= "wrap" > < div class= "box" ></ div ></ div >

css3的translate偏移:
.wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE;position:relative;} .box{width: 100 px;height: 100 px;background:red;position:absolute;top: 50 %;left: 50 %;-webkit-transform: translate(- 50 %,- 50 %);-ms-transform: translate(- 50 %,- 50 %);-o-transform: translate(- 50 %,- 50 %);transform: translate(- 50 %,- 50 %);}< div class= "wrap" > < div class= "box" ></ div ></ div >

表格布局:
.wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE;display:table;} .box{background:red;display:table-cell;text-align:center;vertical-align: middle ;}< div class= "wrap" > < div class= "box" >转换为表格</ div ></ div >

css3中的display:box;
. wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE ;display: -webkit-box;-webkit-box-pack:center;-webkit-box-align:center;} . box{background:red;width: 100 px;height: 100 px;} < div class = "wrap" > < div class = "box" > box < /div > < /div >
弹性布局display:flex:
.wrap{width: 400 px;height: 400 px;border: 1 px solid #EEE;display: flex;justify-content: center;align- items : center;}.box{background:red;width: 100 px;height: 100 px;}<div class= "wrap" > <div class= "box" >box</div></div>

猜你喜欢

转载自blog.csdn.net/qq_25461519/article/details/81002795