水平居中布局请移步至:水平居中布局
一、height 已知
结构:
<div id="parent">
<div id="child"></div>
</div>
样式:
#parent {
width: 400px;
height: 300px;
background-color: lightskyblue;
}
#child {
width: 80px;
height: 60px;
background-color: lightpink;
}
1、position: absolute + margin-top
- 传统方案
- 推荐指数:☆☆☆☆☆
#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
margin-top: -30px;
}
2、position: absolute + calc()
- Can I use ?
- 推荐指数:☆☆☆☆(兼容性较差)
#parent {
position: relative;
}
#child {
position: absolute;
top: calc(50% - 30px);
}
二、height 未知
结构:
<div id="parent">
<div id="child">hello world</div>
</div>
样式:
#parent {
width: 400px;
height: 300px;
background-color: lightskyblue;
}
#child {
width: fit-content;
background-color: lightpink;
}
1、display: flex + align-items: center
- 移动端主流方案
- Can I use ?
- 推荐指数:☆☆☆☆☆
#parent {
display: flex;
align-items: center;
}
2、display: grid + align-items: center
- Can I use ?
- 推荐指数:☆☆☆(大材小用;兼容性较差)
#parent {
display: grid;
align-items: center;
}
3、position: absolute + transform: translateY()
- Can I use ?
- 推荐指数:☆☆☆☆(兼容性较差)
#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
4、display: table-cell + vertical-align: middle
- 类似于
<td valign="middle"> - Can I use ?
- 推荐指数:☆☆☆(邪门歪道)
#parent {
display: table-cell;
vertical-align: middle;
}
5、line-height = height
- 子元素的
line-height值 = 父元素的height值 - 单行文本垂直居中
- 推荐指数:☆☆☆☆(适用场景有局限性)
#child {
line-height: 150px;
}