批改状态:合格
老师批语:注意属性分为容器和项目二类
在
CSS中使用display:flex;,即可使元素转为弹性盒子,子元素同时转为弹性元素,会根据父元素设定的弹性属性自动排列位置。
代码实例:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>flex实例</title><style>.container {width: 300px;display: flex;}.container > .item {width: 60px;}</style></head><body><div class="container"><div class="item">1</div><div class="item">2</div><div class="item">3</div></div></body></html>
运行效果:
flex属性justify-content:控制所有项目在主轴上的对齐方式
justify-content: flex-start; /*起点对齐*/justify-content: flex-end;/*结束对齐*/justify-content: center; /*居中对齐*/justify-content: space-between; /*两端对齐,中间剩余空间平均分配*/justify-content: space-around; /*分散对齐,项目两侧全部平均分配*/justify-content: space-evenly; /*分散对齐,剩余空间平均分配*/
align-content:多行容器项目排列方式
注意,使用多行容器前必须设置
flex-wrap:wrap,意思是将弹性盒子设置为多行。
align-content: stretch;/*默认,以元素自身宽度或高度以主轴顺序对齐,根据元素数量自动填满交叉轴空间*/align-content: flex-start;/*以主轴方向的起始位顺序对齐,忽略原元素交叉轴方向大小值,只取项目内容值的大小来显示项目*/align-content: flex-end;/*以主轴方向的结尾处开始前前对齐,忽略原元素交叉轴方向大小值*/align-content: center;/*以主轴方向排列,并以交叉轴方向居中对齐,忽略原元素交叉轴方向大小值*//* 2. 容器剩余空间在所有项目“之间”的如何分配 ,将项目视为一个个独立的个体*/align-content: space-between;/*两端对齐,中间剩余空间平均分配*/align-content: space-around;/*分散对齐,项目两侧全部平均分配*/align-content: space-evenly;/*分散对齐,剩余空间平均分配*/
align-items:交叉轴项目排列方式
/* 项目在交叉轴上默认是自动伸缩的 */align-items: stretch;/* 项目在交叉轴起始位对齐排列 */align-items: flex-start;/* 项目在交叉轴结尾处对齐排列 */align-items: flex-end;/* 项目在交叉轴上居中 */align-items: center;
order:控制项目顺序
.container > .item:first-of-type {/* order: 将第一个项目移动到第三个项目的位置上 */order: 3;}
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>利用flex制作导航</title><style>/* 初始化 */* {padding: 0;margin: 0;box-sizing: border-box;}a {text-decoration: none;color: #ccc;}nav {height: 40px;background-color: #333;padding: 0 50px;/* 转为弹性盒布局 */display: flex;}nav a {height: inherit;line-height: 40px;padding: 0 15px;}nav a:hover {background-color: seagreen;color: white;}/* 登录/注册放在最右边 */nav a:last-of-type {margin-left: auto;}</style></head><body><header><nav><a href="">首页</a><a href="">教学视频</a><a href="">社区问答</a><a href="">资源下载</a><a href="">登录/注册</a></nav></header></body></html>
运行效果:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号