【css】居中方案

html-css011

【css】居中方案,第1张

前言:根据最近学习的课程,简单总结一下学习到的css左右布局以及居中方案。后期学习深入之后再回来进行css居中的完整总结。

给所有子元素添加 float: left ,给父元素加 clearfix 类,清除浮动

html:

css:

将内联元素外部的块级元素的 text-align 设置为 center ,即可实现内联元素( inline 、 inline-block )的水平居中。

演示

将固定宽度的块级元素的 margin-left 和 margin-right 设置为 auto ,即可实现块级元素的水平居中。

演示

将每个块级元素的 display 设置为 inline-block ,然后将它们的父容器的 text-align 设置为 center ,即可使多个块级元素水平居中。

演示

设置内联元素的行高( line-heigt )和内联元素的父元素的高度( height )相等,且内联元素的字体大小远小于行高,即可使内联元素垂直居中。

演示

通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半,即可实现垂直居中。

演示

借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中

演示

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

第一种 借助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的用法这种方法还没有得到浏览器的普遍支持,如有兴趣,自行学习