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

html-css09

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/