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

2020-06-0606:26:11网页制作Comments2,123 views字数 1120阅读模式

使用flex弹性布局可以比较轻松的实现居中效果,无论是垂直方位还是水平方位。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/19420.html

代码实例如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/19420.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
<!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元素设置为弹性布局,然后再利用如下两行代码实现水平和垂直居中:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/19420.html

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

特别说明:将box元素设置为弹性布局之后,它内部的子项目就会失去一些特性,比如div块级元素不会在水平方向上铺满它的父元素,当然我们也可以设置此div的尺寸,代码实例如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/19420.html

[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>
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/zhizuo/19420.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/zhizuo/19420.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定