1. 文本在容器中程度垂直居中
tac = text-align: center; 程度居中
vam = vertical-align: middle;
1.1 table(table + tac + vam)
父容器:display: table;子容器:display: table-cell; text-align: center; vertical-align: middle;
<div class="container"> <div class="box box1">1</div> <div class="box box2">2</div> <div class="box box3">3</div></div>
.container { display: table;}.box { display: table-cell; width: 150px; height: 150px; text-align: center; vertical-align: middle; border: 1px solid #00f}
1.2. height & line-height + tac
容器(指搁置文本的容器):设置height 将line-height设置与height同高 text-align: center;
html构造与1.雷同,不过不须要父元素container
.box { width: 150px; height: 150px; line-height: 150px; text-align: center; border: 1px solid #00f}
2. 子元素在父元素中程度垂直居中
posa = position: absolute;
2.1 定位 + transform
父容器带有 relative、absolute、fixed的其中一种定位子容器:position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
<div class="container"> <div class="box box1">盒子</div></div>
.container { margin-top: 200px; margin-left: 200px; width: 450px; height: 450px; border: 2px solid #be572a; position: relative;}.box { width: 100px; height: 100px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid #00f}
子容器设置相对定位后,间隔父容器的宽高比是依据父容器的宽高来决定的
所以咱们须要设置top: 50%; left: 50%;
这时,咱们看到,只有盒子的左上角是程度垂直居中的
而后,咱们还须要“移回去”;子容器设置的translate是依据本身宽高来挪动的,所以咱们在移回本身宽高的50%即可失去盒子的程度垂直居中
补充:既然translate挪动的是本身的宽高,所以如果父容器已定宽高,则子容器能够设置margin-top和margin-left也能够达到程度垂直居中的成果
2.2 display:flex
为了与上例辨别扩充了子元素的宽高
父元素: display: flex; align-items: center; justify-content: center;
父元素设置flex后设置justify-content和align-items管制子元素在主轴和穿插轴上的对齐形式
<div class="container"> <div class="box box1">我是flex</div></div>
.container { margin-top: 200px; margin-left: 200px; width: 450px; height: 450px; border: 2px solid #be572a; display: flex; align-items: center; justify-content: center;}.box { width: 150px; height: 150px; border: 1px solid #00f}
3. 程度居中
1.1(当子元素设置了相对定位时的)margin 0 auto
父容器带有 relative、absolute、fixed的其中一种定位子容器:position:absolute; left: 0; right: 0; margin: 0 auto;
<div class="container"> <div class="box box1">left right拉扯了宽度,margin 0 auto管制程度居中</div></div>
.container { margin-top: 200px; margin-left: 200px; width: 450px; height: 200px; border: 2px solid #be572a; position: relative;}.box { width: 200px; height: 150px; position: absolute; left: 0; right: 0; margin: 0 auto; border: 1px solid #00f}
其实这里有人会纳闷,父容器曾经设置了宽高,那间接margin 0 auto不就好了吗?
那是在子容器没有设置相对定位的状况下能够间接margin 0 auto
如果咱们因为须要,在子容器设置了相对定位,那即便父容器设置了宽高,子容器margin 0 auto也不会有程度居中成果
/*left: 0; right: 0;*/