CSS一个盒子在另一个盒子水平垂直居中

html-css039

CSS一个盒子在另一个盒子水平垂直居中,第1张

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

1、 使用定位,左右拉取方法:

2、使用margin:auto,方法:

1、使用位移方法,兼容性较低,移动端慎用

2、组合使用display:table-cell和vertical-align、text-align,使父元素内的所有行内元素水平垂直居中(内部div设置display:inline-block即可)。

3、用弹性布局实现垂直左右居中

第一步:在img标签后面添加一个span元素

第二步:为这几个元素设置样式

1.把#div1元素设置text-align:center

2.把添加的元素span转化为行内块元素(display:inline-block),并且设置vertical-align:middle

3.为img元素设置vertical-align:middle。

完成以上操作之后,这个Img元素在#div1中就是垂直居中的了,这种方法的兼容性等比较好,唯一的缺点可能就是要在元素后面添加一个元素

(注意:这个元素最好是span元素,如果是div元素的话,在低版本ie下有兼容问题)

这种方法利用了css3的新特性

为#div1设置display:flexvertical-align:middlealign-items:middle。

这种方法的缺点就是只要不支持css3的浏览器,那就不会起作用了。

盒子居中是相对于父元素来说的,因此我们让盒子居中时,往往采用嵌套的方式,让父盒子套着子盒子 。

在父子盒子嵌套下,让子盒子居中的方式:

第一种方法:position, 使用定位,子绝父相,再left:50%,margin-left:负的盒子宽度的一半,这是最常用的方法

第二种方法:flex,弹性布局,让子盒子居中,但是样式要写在父盒子中,display:flex,just-content:center

第三种方法:在position基础上,把margin-left换成CSS3中的transform:translate(-50px)

第四种方法:在position的基础上,只保留子绝父相,然后在子盒子中加上margin:auto、left:0、right:0;