不想过多赘述,目的很清楚。我要在A盒子中水平垂直居中B,常规方式就不上了,方法很多。这里我只笔记两种比较特别的。
【上代码】
方法一:
html:
<div class="Aa"><div class="Bb">This is my world</div></div>
css:
.Aa {
width: 400px;
height: 400px;
border: 1px solid red;
position: relative;
}
.Bb {
position: absolute;
left: 50%; (父容器的50%)
top: 50%; (父容器的50%)
transform: translate(-50%, -50%); (自身的50%)
background-color: pink;
}
方法二:
html:
<div class="Aa"><div class="Bb">This is my world</div></div>
css:
.Aa {
width: 400px;
height: 400px;
border: 1px solid red;
position: relative;
}
.Bb {
width: 200px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
方法一对于 IE8- 不支持
方法二兼容性更好
方法一的原理也很简单,就不说明了。
说下方法二吧。
当一个绝对定位元素,其对立定位方向属性同时有具体的定位数值的时候,流体特性就发生了。
具有流体特性绝对定位元素的margin:auto
的填充规则和普通流体元素一模一样:
1:如果一侧定值,一侧auto
,auto
为剩余空间大小;:
2:如果两侧均是auto
, 则平分剩余空间;