伸缩盒模型(flexbox)是一个新的盒子模型,主要优化了UI布局。作为实际布局的第一个CSS模块(浮动真的应该主要用来制作文本围绕图片这样的效果),它使很多任务容易多。Flexbox的功能主要包手:简单使用一个元素居中(包括水平垂直居中),可以让扩大和收缩元素来填充容器的可利用空间,可以改变源码顺序独立布局,以及还有其他的一些功能。
下面我们来看一个简单的实例:(使用Flexbox实现水平垂直居中)
<!DOCTYPE html>
<html>
<head>
< charset=\"utf-8\">
< name=\"viewport\" content=\"width=device-width\">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
}
.flex-container {
height: 100%;
padding: 0;
margin: 0;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;
}
.row {
width: auto;
border: 1px solid blue;
}
.flex-item {
background-color: tomato;
padding: 5px;
width: 20px;
height: 20px;
margin: 10px;
line-height: 20px;
color: white;
font-weight: bold;
font-size: 2em;
text-align: center;
}
</style>
</head>
<body>
<div class=\"flex-container\">
<div class=\"container\">
<div class=\"row\">
<span class=\"flex-item\">1</span>
</div>
<div class=\"row\">
<span class=\"flex-item\">2</span>
</div>
<div class=\"row\">
<span class=\"flex-item\">3</span>
</div>
<div class=\"row\">
<span class=\"flex-item\">4</span>
</div>
</div>
</div>
</body>
</html>
缺省flexbox布局使用两个坐标来定位元素。 主要属性是flex-direction(只可以是row或者column),缺省值是row
为了让元素居中,我们使用如下方式:
- 使用flex布局,即,display设置为flex
- justify-content定义了flex元素将会根据主要坐标对齐(本例中是水平方向)
- align-items将在本例中处理垂直方向
继续阅读与本文标签相同的文章
-
第16问:Filecoin从DSN角度解读
2026-05-14栏目: 教程
-
C/C+从零基础到精通,究竟是如何快速完成的?其实只需要这6步!
2026-05-14栏目: 教程
-
谷歌再爆重大安全漏洞!华为却成最大赢家?网友:这谁还敢用!
2026-05-14栏目: 教程
-
Excel崩溃文件如何找回
2026-05-14栏目: 教程
-
又一外国巨头宣布退出中国,关闭120家店,网友:中国钱不好赚了!
2026-05-14栏目: 教程
