水平居中
1.行内级元素:
设置父元素的text-align: center
1 2 3 4 5
| .container { height: 300px; background-color: orange; text-align: center; }
|
1 2 3
| <div class="container"> <span>剧中</span> </div>
|
2.块级元素
设置当前块级元素(宽度) margin: 0 auto;
不设置宽度,块级元素默认占一行,看不出效果
1 2 3 4 5 6 7 8 9 10
| .container { height: 300px; background-color: orange; }
.box1 { width: 100px; margin: 0 auto; background-color: #f00; }
|
1 2 3
| <div class="container"> <div class="box1">居中</div> </div>
|
3.绝对定位
元素有宽度情况下, left0/right0/margin: 0 auto;
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .container { position: relative; height: 300px; background-color: orange; }
.box2 { position: absolute; width: 100px; left: 0; right: 0; margin: 0 auto; background-color: #f00; }
|
1 2 3
| <div class="container"> <div class="box2">居中</div> </div>
|
4.flex
justify-content: center
1 2 3 4 5 6 7 8 9 10 11
| .container { display: flex; justify-content: center; height: 300px; background-color: orange; } .box3 { width: 100px; height: 100px; background-color: #f00; }
|
1 2 3
| <div class="container"> <span class="box3">居中</span> </div>
|
垂直居中
1.垂直居中: 绝对定位
元素有高度情况下, top0/bottom0/margin: auto 0;
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .one { position: relative; height: 300px; background-color: orange; }
.two { position: absolute; height: 100px; top: 0; bottom: 0; margin: auto 0; background-color: red; }
|
1 2 3 4 5
| <div class="one"> <div class="two"> 居中 </div> </div>
|
弊端:
1> 必须使用定位(脱离标准流)
2> 必须给元素设置高度
flex布局(直接使用flex)
1 2 3 4 5 6 7 8 9 10 11
| .one { display: flex; align-items: center; height: 300px; background-color: orange; }
.two { background-color: red; }
|
1 2 3 4 5
| <div class="one"> <div class="two"> 居中 </div> </div>
|
弊端:
1> 当前flex局部中所有的元素都会被垂直居中
2> 相对来说, 兼容性差一点点(基本可以忽略)
top/translate
1 2 3
| 两件事情: 1.让元素向下位移父元素的50% 2.让元素向上位移自身的50%
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .one { height: 300px; background-color: orange; }
.two { display: inline-block; position: relative; height: 100px; top: 50%; transform: translate(0, -50%); background-color: red; }
|
1 2 3 4 5
| <div class="one"> <div class="two"> 居中 </div> </div>
|