CSS水平居中与垂直居中的总结

html-css07

CSS水平居中与垂直居中的总结,第1张

1. 设置 margin: 0 auto

单行文本垂直居中,通过设置行高为父元素高度(父元素高度已知)。

图片垂直居中,设置上下padding(父元素高估不设置)。

图片垂直居中,下边这种方法会有一定偏差(父元素高估不设置)。

图片垂直居中,图片作为背景。

1. 若元素是行内块级元素, 基本思想是使用display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央。

行内元素可可以转换为inline-block实现居中。

链接: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%)}