css子元素如何在父元素中居中

html-css018

css子元素如何在父元素中居中,第1张

1、定位+margin:auto 父元素 position: relative 子元素 position: absolute

left:0top:0right:0bottom:0margin: auto

2、定位+margin-left+margin-top 父元素 position: relative 子元素 position:absolute

left:50%top:50%margin-left: -当前盒子宽度的一半margin-top: -当前盒子高度的一

3、定位+transfrom(子元素未知宽高)父元素 position: relative 子元素 position:

absolute left:50%top:50%transform: translate(-50%,-50%)• 弹性盒子父元素 display:

flexjustify-content: centeralign-items: center

4、flex+margin: auto 父元素 display: flex子元素 margin:auto

html结构

1.position

这样就可以看到子元素在父元素居中啦!

2. flex

小结:

第一种方法 适用于有固定宽高的子元素 但是不会受制于浏览器的兼容性 

第二种方法 在子元素不固定宽高也适用 但是受制于浏览器的兼容性 不过现在主流的浏览器都支持flex了

ps:浏览器兼容性查验推荐 https://caniuse.com/

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