flex弹性布局:水平、垂直居中代码实例

使用flex弹性布局可以比较轻松的实现居中效果,无论是垂直方位还是水平方位。

代码实例如下:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
 <style>
.box{
  height:400px;
  background: #B4D3F7;
  display: flex;
  justify-content: center;
  align-items: center;
}
.item{
  background: #F7E8B4;
}
</style>
</head>
<body>
  <div class="box">
    <div class="item">蚂蚁部落</div>
  </div>
</body>
</html>

将box元素设置为弹性布局,然后再利用如下两行代码实现水平和垂直居中:

[CSS] 纯文本查看 复制代码
1
2
justify-content: center;
align-items: center;

特别说明:将box元素设置为弹性布局之后,它内部的子项目就会失去一些特性,比如div块级元素不会在水平方向上铺满它的父元素,当然我们也可以设置此div的尺寸,代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
 <style>
.box{
  height:400px;
  background: #B4D3F7;
  display: flex;
  justify-content: center;
  align-items: center;
}
.item{
  background: #F7E8B4;
  width:600px;
  height:300px;
  text-align:center;
  line-height:300px;
}
</style>
</head>
<body>
  <div class="box">
    <div class="item">蚂蚁部落</div>
  </div>
</body>
</html>
THE END