CSS3中的弹性盒子
布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现;2009年,W3C提出了一种新的方案—Flex布局,可以简便、完整、响应式地实现各种页面布局。目前,它已经得到了所有浏览器的支持,这意味着,现在就能很安全地使用这项功能。
弹性盒子是 CSS3 的一种新的布局模式。引入弹性盒布局模型的目的是提供一种更加有效的方式来对一个容器中的子元素进行排列、对齐和分配空白空间。
组成内容
弹性盒子由弹性容器和弹性子元素组成。 弹性容器通过设置 display 属性的值为 flex 或 inline-flex将其定义为弹性容器。 弹性容器内包含了一个或多个弹性子元素。
使用
1.基本用法
<style>
.flex-container{
display: flex;
width: 450px;
height: 150px;
background-color: darkcyan;
}
.flex-item{
width: 130px;
height: 125px;
margin: 10px;
background-color: yellowgreen;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>
2.flex-direction使用(弹性子元素在父容器中的位置)
<style>
.flex-container{
display: flex;
width: 450px;
background-color: darkcyan;
flex-direction: row-reverse;
}
.flex-item{
width: 130px;
height: 125px;
margin: 10px;
background-color: yellowgreen;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>
3.justify-content 的使用(弹性子元素在父容器中的位置) 如下:盒子居中显示
<style>
.flex-container{
display: flex;
width: 500px;
background-color: darkcyan;
justify-content: center;
}
.flex-item{
width: 130px;
height: 125px;
margin: 10px;
background-color: yellowgreen;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>
4.align-items的使用(设置或检索弹性盒子元素在副轴(y轴)方向上的对齐方式)如下:从底部开始显示
<style>
.flex-container{
display: flex;
width: 500px;
height: 211px;
background-color: darkcyan;
align-items: flex-end;
}
.flex-item{
width: 130px;
height: 125px;
margin: 10px;
background-color: yellowgreen;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>
5.flex-wrap的使用(定弹性盒子的子元素换行方式)如下:自动换行
<style>
.flex-container{
display: flex;
width: 300px;
background-color: darkcyan;
flex-wrap:wrap;
}
.flex-item{
width: 130px;
height: 125px;
margin: 10px;
background-color: yellowgreen;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>
6.flex 用于指定弹性子元素如何分配空间。(弹性子元素占比)
<style>
.flex-container{
display: flex;
width: 400px;
height: 165px;
background-color: darkcyan;
}
.flex-item{
margin: 10px;
background-color: yellowgreen;
}
.one{
flex: 2;
}
.tow{
flex: 1;
}
.three{
flex: 1;
}
</style>
<body>
<div class="flex-container">
<div class="flex-item one">盒子1
</div>
<div class="flex-item tow">盒子2
</div>
<div class="flex-item three">盒子3
</div>
</div>
</body>