css绝对居中几种方法

html-css041

css绝对居中几种方法,第1张

水平或者垂直居中单一的要求很好做到,我说几种自己总结的常用的水平且垂直居中的几种方法:

第一种 借助inline-block的特点

#d1{

display:inline-block

width:500px

height:500px

border:1px solid red

text-align:center

}

#d1:after{

content:""

display:inline-block

height:100%

vertical-align:middle

background:#000

}

#d2{

display:inline-block

width:200px

height:200px

border:1px solid red

vertical-align:middle

}

<div id="d1">

<div id="d2"></div>

</div>

第二种 利用css的transform 好用但是兼容性不好,IE10+以及其他现代浏览器才支持(手机开发可忽略)

.box{width:300pxheight:300pxborder:1px solid redposition:relative}

.content{

position:absolute

width:100px

height:100px

border:1px solid red

margin:0 auto

top:50%left:50%

/* transform:translateY(-50%)仅垂直居中*/

/* transform:translateX(-50%)仅水平居中*/

transform: translate(-50%, -50%)

/*

若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可

父元素{

height:xxx

}

.子元素 {

position: relative

top: 50%

transform: translateY(-50%)

}

*/

}

<div class="box">

<div class="content"></div>

</div>

第三种:绝对定位之后的偏移

.box{

border:1px solid red

width:300pxheight:300pxposition:relative

}

.content{

border:1px solid red

width: 200pxheight: 200px

position: absoluteleft: 50%top: 50%

margin-top: -100px /* 高度的一半 */

margin-left: -100px /* 宽度的一半 */

}

<div class="box">

<div class="content"></div>

</div>

第四种:定位之后的margin: auto

.box{

border:1px solid red

width:300pxheight:300pxposition:relative

}

.content{

width: 200px

height: 200px

position: absolute

left: 0

top: 0

right: 0

bottom: 0

margin: auto

border:1px solid red

}

<div class="box">

<div class="content"></div>

</div>

第五种 flex布局

<div style="display:flexdisplay: -webkit-flexjustify-content:centeralign-items:centerwidth: 300pxheight: 300pxborder:1px solid red">

<div style="width: 200pxheight: 200pxborder:1px solid red"></div>

</div>

第六种利用display:table-cell的vertical-align属性 子元素加上“display:inline-block”可水平居中

<div style="display:table-cellvertical-align:middletext-align:centerwidth:300pxheight:300pxborder:1px solid red">

<div style="border:1px solid redwidth:200pxheight:200pxdisplay:inline-block"></div>

</div>

第七种 使用css3中的display:-webkit-box的用法这种方法还没有得到浏览器的普遍支持,如有兴趣,自行学习

1.兼容性不错的主流用法是:(但,这种方法有一个很明显的不足,就是需要提前知道元素的尺寸。否则margin负值的调整无法精确。此时,往往要借助JS获得。)

.conter{

width: 600pxheight: 400px

position: absoluteleft: 50%top: 50%

margin-top: -200px /* 高度的一半 */

margin-left: -300px /* 宽度的一半 */

}

2.CSS3的兴起,使得有了更好的解决方法,就是使用transform代替margin. transform中translate偏移的百分比值是相对于自身大小的,可以这样

.conter{

width: 600pxheight: 400px

position: absoluteleft: 50%top: 50%

transform: translate(-50%, -50%) /* 50%为自身尺寸的一半 */

}

3.margin:auto实现绝对定位元素的居中(上下左右均0位置定位;margin: auto)

.conter{

width: 600pxheight: 400px

position: absoluteleft: 0top: 0right: 0bottom: 0

margin: auto /* 有了这个就自动居中了 */

}

4.使用css3盒模型:flex布局。(不考虑低版本浏览器的情况下)

父容器css:text-align:center图片的css:margin-left:automargin-right:autooverflow:hidden更好的方法是写成背景,这样水平垂直都居中,且不会溢出:在父容器css里写: background:url(xxx.jpg) no-repeat center center