1.flex属性
flex属性定义子项分配剩余的空间,用flex表示占据多数分数
1.1案例一 父项内两边子项固定宽度,中间子项宽度可自适应浏览器屏幕宽度变化
<body>
<section>
<div></div>
<div></div>
<div></div>
</section>
</body>
<style>
section {
width: 60%;
height: 200px;
background-color: orange;
margin: 0 auto;
display: flex;
}
/* 结构伪类选择器 */
section div:nth-child(1){
width: 150px;
height: 200px;
background-color: red;
}
section div:nth-child(2){
flex: 1;
background-color: green;
}
section div:nth-child(3){
width: 150px;
height: 200px;
background-color: skyblue;
}
</style>
父项设置为浏览器宽度的60%,第1个和第3个子项设置宽度设置为150px。
为第2个子项设置flex: 1,则第二个子项独占剩下的空间,且空间为自适应的,可依据浏览器屏幕缩小或放大而改变。
页面效果展示
1.2案例二 三个子项平分父项空间
<body>
<p>
<span>1</span>
<span>2</span>
<span>3</span>
</p>
</body>
<style>
p {
width: 60%;
height: 200px;
background-color: orange;
margin: 10px auto;
display: flex;
}
p span{
flex: 1;
}
</style>
页面效果展示 - 父项空间被子项平分,子项宽度相同
1.3案例三 第2个子项占据空间比其他子项多一份
以案例二为基础,设置第2个子项的flex属性
p span:nth-child(2){
flex: 2;
background-color: red;
}
页面效果展示 - 第2个子项占据空间相比其他子项多一份,且3个子项宽度都是自适应的,可随着浏览器屏幕大小而伸缩
2.align-self 控制子项自己在侧轴上的排序方式
align-self属性允许单个项目有与其他项目不一样的对齐方式,且可覆盖align-items属性。
默认值为auto,表示子项继承父项的align-items属性,如果没有父元素,则效果等同于stretch。
2.1案例 第3个子项单独沿着侧轴排序
<body>
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</body>
<style>
div{
width: 400px;
height: 200px;
background-color: skyblue;
color: white;
/* 父级添加flex属性 */
display: flex;
align-items: flex-end;
}
div span{
width: 75px;
height: 50px;
background-color: red;
margin: 10px;
}
</style>
页面效果展示 - 单独父项设置align-items属性,3个子项都会沿着侧轴排序
如果要第3个子项单独沿着侧轴排序,则为第3个子项设置align-self属性
div span:nth-child(3){
align-self: flex-end;
}
页面效果展示 - 为第3个子项设置align-self属性
3.order属性定义项目的排列顺序
数值越小,排列越靠前,默认值为0。(注意:和z-index不相同)
3.1案例 将第2个子项移到第1个子项前面
默认值为0,为第 2个子项设置属性值order: -1
div span:nth-child(2){
order: -1;
}
页面效果展示