【css】居中方案

html-css09

【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%的方法实现垂直居中

演示

链接:https://zhuanlan.zhihu.com/p/39437057

第一种:利用负的margin来进行居中,需要知道固定宽高,限制比较大。

body>div:nth-of-type(1){ width:400pxheight:400pxbackground:#ff0position:relativemargin-bottom:10px}

body>div:nth-of-type(1)div{ width:100pxheight:100pxbackground:#0f0position:absolutetop:50%left:50%margin-left:-50pxmargin-top:-50px}

第二种:利用绝对定位居中,非常常用的一种方法。body>div:nth-of-type(2){ width:400pxheight:400pxbackground:#ff0position:relativemargin-bottom:10px}

body>div:nth-of-type(2) div{ width:100pxheight:100pxbackground:#0f0position:absolutetop:0left:0right:0bottom:0margin:auto}

第三种:使用flex布局(.min宽高可不固定)

body>div:nth-of-type(3){ width:400pxheight:400pxbackground:#ff0margin-bottom:10pxdisplay:flex}

body>div:nth-of-type(3) div{ width:100pxheight:100pxbackground:#0f0margin:auto }

第四种:flex居中(演示)。CSS3中引入的新布局方式,比较好用。缺点:IE9以及IE9一下不兼容。

body>div:nth-of-type(4){ width:400pxheight:400pxbackground:#ff0margin-bottom:10pxdisplay:flexjustify-content:centeralign-items:center}

body>div:nth-of-type(4) div{ width:100pxheight:100pxbackground:#0f0}

第五种:利用table-cell来控制垂直居中。

body>div:nth-of-type(5){ width:400pxheight:400pxbackground:#ff0margin-bottom:10pxvertical-align:middledisplay:table-celltext-align:center}

body>div:nth-of-type(5) div{ width:100pxheight:100pxbackground:#0f0display:inline-block }

第六种:利用空盒子做外容器,里边的块元素会自动垂直居中,只需要控制一下水平居中就可以达到效果。

body>div:nth-of-type(6){ width:400pxheight:400pxbackground:#ff0margin-bottom:10pxtext-align:center vertical-align:middle}

body>div:nth-of-type(6) div{ width:100pxheight:100pxbackground:#0f0display:inline-blockvertical-align:middle}

body>div:nth-of-type(6) span{ width:0height:100%display:inline-blockvertical-align:middle}

第七种:这种方法灵活运用CSS中transform属性,较为新奇。缺点是IE9下不兼容。

body>div:nth-of-type(7){ width:400pxheight:400pxbackground:#ff0position:relativemargin-bottom:10px}

body>div:nth-of-type(7) div{ width:100pxheight:100pxbackground:#0f0position:absolutetop:50%left:50%transform:translate(-50%,-50%)}