CSS 加油包之垂直居中

133 阅读1分钟

1. display:table; vertical-align:middle

🌰 举例

<!--html-->
<div id="box">
    <div id="child">text vertical-align
  文字垂直居中~</div>
</div>
/* CSS */
#box {
    width: 300px;
    height: 300px;
    background: orange;
    display: table;
    color: white;
}
#child {
  padding: 0 0 0 20px;
    display: table-cell;
    vertical-align: middle;
}

⬅️ 效果图


2. position:absolute; transform: translate

🌰 举例

  <!--html-->
<div id="box">
    <div id="child">文字垂直居中</div>
</div>
/* CSS */
#box {
    border: 1px solid pink;
    width: 300px;
    height: 300px;
    background: #efefef;
    position: relative;
}
#child {
    background: pink;
    color: white;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}

⬅️ 效果图


3. position:absolute; translate -50%

🌰 举例

  <!--html-->
<div id="box">
    <div id="child">垂直居中</div>
</div>
/* CSS */
#box {
    width: 300px;
    height: 300px;
    background: orange;
    position: relative;
}
#child {
    background: midnightblue;
    color: white;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}

⬅️ 效果图


4. position:absolute; margin:auto

🌰 举例

  <!--html-->
<div id="box">
    <div id="child">文字垂直居中</div>
</div>
/* CSS */
#box {
    width: 300px;
    height: 300px;
    background: skyblue;
    border: 3px solid grey;
    position: relative;
}
#child {
    width: 200px;
    height: 100px;
    background: grey;
    color: white;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    line-height: 100px;
}

⬅️ 效果图


5. display:flex; align-items:center

🌰 举例

<!--html-->
<div id="box">文字垂直居中</div>
/* CSS */
#box {
    width: 300px;
    height: 300px;
    background: royalblue;
    color: yellow;
    display: flex;
    align-items: center;
}

⬅️ 效果图


6. grid

  • 可以使用 display:grid; 再设置两个辅助元素实现垂直居中 🌰 举例
<!--html-->
<!--html-->
<div id="box">
    <div class="one"></div>
    <div class="two">居中目标图形</div>
    <div class="three"></div>
</div>
/* CSS */
#box {
  border: 4px solid lightgrey;
    width: 300px;
    height: 300px;
    display: grid;
    color: white;
}
.two {
    background: pink;
}
.one, .three {
    background: skyblue;
}

⬅️ 效果图


7. display:flex; flex-direction:column

  <!--html-->
<div id="box">
    <div id="child"></div>
</div>
/* CSS */
#box {
    width: 300px;
    height: 300px;
    background: royalblue;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
#child {
    width: 300px;
    height: 100px;
    background: yellow;
}

⬅️ 效果图


后话:为什么垂直居中比水平居中难操作?

与CSS的回溯机制有关,可参考相关文章:

medium.com/@isaaclyman…

zhuanlan.zhihu.com/p/31311515

参考文章 | Reference List
MDN: developer.mozilla.org/en-US/docs/… 掘金文章: juejin.cn/post/684490…