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

html-css010

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.横向居中

(1)方法一

position: fixed

/* 居中对齐begin */

left: 50%

/* 兼容老版本的方法 */

-webkit-transform: translateX(-50%)

transform: translateX(-50%)

(2)方法二

设置固定宽度,并且设置margin:auto

(3)方法三

position: fixed

left: 50% - 居中盒子宽度的50%

2.纵向居中

(1) 高度和行高设置一样

height: 100px

line-height:100px

3.横向和纵向都居中

display: flex

/* 默认的主轴是x轴row, justify-content: center 沿着主轴居中对齐 */

justify-content: center

/* 我们需要一个侧轴居中 */

align-items: center

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

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

第一种方法: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;