文章目录
1.Flex布局
1.1 Flex组成
设置方式:给父元素设置 display: flex,子元素可以自动挤压或拉伸
组成部分:
- 弹性容器
- 弹性盒子
- 主轴:默认在水平方向
- 侧轴 / 交叉轴:默认在垂直方向
1.2 主轴对齐方式justify-content
属性名:justify-content
1.3 侧轴对齐方式align-items
/align-self
align-items
:当前弹性容器内所有弹性盒子的侧轴对齐方式(给弹性容器设置)
align-self
:单独控制某个弹性盒子的侧轴对齐方式(给弹性盒子设置)
1.4 修改主轴方向flex-direction
属性名:flex-direction
1.5 弹性伸缩比flex
属性名:flex
属性值:整数数字
,表示占用父级剩余尺寸的份数。
1.6 弹性盒子换行flex-wrap
弹性盒子可以自动挤压或拉伸,默认情况下,所有弹性盒子都在一行显示。
属性名:flex-wrap
属性值
- wrap:换行
- nowrap:不换行(默认)
1.7 行内对齐方式align-content
属性名:align-content
该属性对单行弹性盒子模型无效。
2.浮动
2.1 基本使用
作用:让块元素水平排列。
属性名:float
属性值
- left:左对齐
- right:右对齐
<style>
/* 特点:顶对齐;具备行内块显示模式特点;浮动的盒子会脱标 */
.one {
width: 100px;
height: 100px;
background-color: brown;
float: left;
}
.two {
width: 200px;
height: 200px;
background-color: orange;
/* float: left; */
float: right;
}
</style>
<div class="one">one</div>
<div class="two">two</div>
特点:
- 浮动后的盒子顶对齐
- 浮动后的盒子具备行内块特点
- 浮动后的盒子脱标,不占用标准流的位置
2.2 产品区域布局
HTML标签:
<!-- 版心:左右,右面:8个产品 → 8个 li -->
<div class="product">
<div class="left"></div>
<div class="right">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
CSS样式:
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
.product {
margin: 50px auto;
width: 1226px;
height: 628px;
background-color: pink;
}
.left {
float: left;
width: 234px;
height: 628px;
background-color: skyblue;
}
.right {
float: right;
width: 978px;
height: 628px;
background-color: brown;
}
.right li {
float: left;
margin-right: 14px;
margin-bottom: 14px;
width: 234px;
height: 300px;
background-color: orange;
}
/* 第四个li和第八个li 去掉右侧的margin */
.right li:nth-child(4n) {
margin-right: 0;
}
/* 细节:如果父级宽度不够,浮动的盒子会掉下来 */
</style>
2.3 清除浮动
场景:浮动元素会脱标,如果父级没有高度,子级无法撑开父级高度(可能导致页面布局错乱)
解决方法:清除浮动(清除浮动带来的影响)
场景搭建:
<style>
.top {
margin: 10px auto;
width: 1200px;
/* height: 300px; */
background-color: pink;
}
.left {
float: left;
width: 200px;
height: 300px;
background-color: skyblue;
}
.right {
float: right;
width: 950px;
height: 300px;
background-color: orange;
}
.bottom {
height: 100px;
background-color: brown;
}
</style>
<div class="top">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="bottom"></div>
2.3.1 额外标签法
在父元素内容的最后添加一个块级元素,设置 CSS 属性 clear: both
<style>
.clearfix {
clear: both;
}
</style>
<div class="father">
<div class="left"></div>
<div class="right"></div>
<div class="clearfix"></div>
</div>
2.3.2 单伪元素法
- 准备 after 伪元素
.clearfix::after {
content: "";
display: block;
clear: both;
}
- 父级使用 clearfix 类
<div class="father clearfix"></div>
2.3.3 双伪元素法
- 准备 after 和 before 伪元素
/* before 解决外边距塌陷问题 */
/* 双伪元素法 */
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
/* after 清除浮动 */
.clearfix::after {
clear: both;
}
- 父级使用 clearfix 类
<div class="father clearfix"></div>
2.3.4 overfow法
.father {
margin: 10px auto;
width: 1200px;
/* height: 300px; */
background-color: pink;
overflow: hidden;
}