CSS元素的垂直居中案例
1. 绝对定位
缺点
- 必须使用定位,并且是脱标元素
- 必须给元素设置高度
<div class="container"><div class="box"></div>
</div>
.container {position: relative;width: 300px;height: 300px;background-color: orange;
}
.box {position: absolute;top: 0;bottom: 0;width: 100px;height: 100px;margin: auto 0;background-color: pink;
}
2. flex布局
<div class="container"><div class="box"></div>
</div>
.container {display: flex;align-items: center;width: 300px;height: 300px;background-color: orange;
}
.box {width: 100px;height: 100px;background-color: pink;
}
3. 利用形变
<div class="container"><div class="box"></div>
</div>
.container {width: 300px;height: 300px;background-color: orange;
}
.box {position: relative;top: 50%;width: 100px;height: 100px;background-color: pink;transform: translateY(-50%);
}
4. 行内元素的垂直居中
利用行盒的概念,待补充