元素在页面上居中,特别是垂直居中,在过去使用css是出了名的困难,我们不得不解决许多问题。不过,值得庆幸的是,Flexbox让这一切变得更容易,我们现在可以将设计精力集中到更高层次的问题上。
以下是使用Flexbox的定心元件的简单指南。
水平居中
让我们从一个div开始,它包含两个段落,我们希望它们在同一轴上水平居中。这就像在容器上使用值为 center 的justify-content属性一样简单:
arrr!
yeehaw!
1<div class="box flex">
2 <p>
3 <img src="/images/pirate.svg" width="75">
4 arrr!
5 </p>
6 <p>
7 <img src="/images/cowboy.svg" width="75">
8 yeehaw!
9 </p>
10</div>
1.box.flex {
2 display: flex;
3 justify-content: center;
4}
5
6.box {
7 padding: .5rem;
8 height: 300px;
9 box-shadow: 2px 2px 5px rgba(0,0,0,0.03);
10 border-radius: 4px;
11
12 color: #84613D;
13 font-family: "Lucida Console", Monaco, monospace;
14 background: #FDF9EA;
15 border-bottom: 1px solid #F9F2D6;
16 border-right: 1px solid #F9F2D6;
17}
18
19.box p {
20 max-width: 125px;
21 text-align: center;
22 background: rgba(255,255,255,0.5);
23 margin: .25rem;
24 padding: .25rem;
25}
垂直居中
当我们还需要将元素垂直居中时,Flexbox的功能真的很强大。以下是我们的示例,但Flex项目也垂直居中:
1.box.flex {
2 display: flex;
3 justify-content: center;
4 align-items: center;
5}
arrr!
yeehaw!
如果你只是想让特定的flex项目垂直居中,你可以在项目上设置self-self:
1.flex p:last-child {
2 align-self: center;
3}
arrr!
yeehaw!
整页垂直居中
如果你想把一个元素放在页面的死角,这可能会有点麻烦,因为弹性项只会根据其容器的高度垂直居中。这意味着容器本身需要与页面本身的高度相同。这很容易-使用VIEPORT units,]就足够了,其中100vh 是视区高度的100%。
下面是一个简单的例子:
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
7 <title>Dead center!</title>
8 <style>
9 body {
10 margin: 0;
11 }
12
13 .center-me {
14 display: flex;
15 justify-content: center;
16 align-items: center;
17
18 height: 100vh;
19 }
20 </style>
21 </head>
22 <body>
23
24 <div class="center-me">
25 <p>😇 Bonjour center!</p>
26 </div>
27
28 </body>
29</html>
<$>[注意]还要注意,我们确保将页面的页边距重置为0,否则您最终会得到一点滚动。<$>