目录
1.浮动的作用
块标签在一行完美的体现
让垂直布局的盒子变成水平布局,如:一个在左,一个在右
-
属性名:float
-
属性值:
属性名 效果 left 左浮动 right 右浮动
-
浮动元素会脱离标准流(简称:脱标),在标准流中不占位置 • 相当于从地面飘到了空中
-
浮动元素比标准流高半个级别,可以覆盖标准流中的元素
-
浮动找浮动,下一个浮动元素会在上一个浮动元素后面左右浮动
-
浮动元素有特殊的显示效果
• 一行可以显示多个
• 可以设置宽高
浮动后不能设置图片居中 还有文字居中
<style>
/* 浮动的标签 是顶对齐的 */
/* 浮动:在一行排列,宽高生效 --浮动后的标签具备行内块元素的特点 */
.one {
width: 100px;
height: 100px;
background-color: pink;
float: left;
margin-top: 50px;
}
.two {
width: 200px;
height: 200px;
background-color: skyblue;
float: left;
}
.three {
width: 300px;
height: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</body>
2.清除浮动
能够认识 清除浮动的目的,并且能够使用 清除浮动的方法
1.清除浮动的方法 — ① 直接设置父元素高度
• 优点:简单粗暴,方便
• 缺点:有些布局中不能固定父元素高度。如:新闻列表、京东推荐模块
<style>
.top {
margin: 0 auto;
width: 1000px;
/* height: 300px; */
background-color: pink;
}
.bottom {
height: 100px;
background-color: green;
}
.left {
float: left;
width: 200px;
height: 300px;
background-color: #ccc;
}
.right {
float: right;
width: 790px;
height: 300px;
background-color: skyblue;
}
</style>
</head>
<body>
<!-- 父子级标签, 子级浮动, 父级没有高度, 后面的标准流盒子会受影响, 显示到上面的位置 -->
<div class="top">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="bottom"></div>
</body>
2.清除浮动的方法 — ② 额外标签法
➢ 操作:
-
在父元素内容的最后添加一个块级元素
-
给添加的块级元素设置 clear:both
➢ 特点:
• 缺点:会在页面中添加额外的标签,会让页面的HTML结构变得复杂
<style>
.top {
margin: 0 auto;
width: 1000px;
/* height: 300px; */
background-color: pink;
}
.bottom {
height: 100px;
background-color: green;
}
.left {
float: left;
width: 200px;
height: 300px;
background-color: #ccc;
}
.right {
float: right;
width: 790px;
height: 300px;
background-color: skyblue;
}
.clearfix {
/* 清除左右两侧浮动的影响 */
clear: both;
}
</style>
</head>
<body>
<!-- 父子级标签, 子级浮动, 父级没有高度, 后面的标准流盒子会受影响, 显示到上面的位置 -->
<div class="top">
<div class="left"></div>
<div class="right"></div>
<div class="clearfix"></div>
</div>
<div class="bottom"></div>
</body>
3.清除浮动的方法 — ③ 单伪元素清除法
①:基本写法
②:补充写法
项目中使用,直接给标签加类即可清除浮动
<style>
.top {
margin: 0 auto;
width: 1000px;
/* height: 300px; */
background-color: pink;
}
.bottom {
height: 100px;
background-color: green;
}
.left {
float: left;
width: 200px;
height: 300px;
background-color: #ccc;
}
.right {
float: right;
width: 790px;
height: 300px;
background-color: skyblue;
}
/* 单伪元素清除浮动 和 额外标签法原理是一样的 */
.clearfix::after {
content: '';
/* 伪元素添加的标签是行内,要求块 */
display: block;
clear: both;
/* 为了兼容性 */
height: 0;
visibility: hidden;
}
</style>
</head>
<body>
<!-- 父子级标签, 子级浮动, 父级没有高度, 后面的标准流盒子会受影响, 显示到上面的位置 -->
<div class="top clearfix">
<div class="left"></div>
<div class="right"></div>
<!-- 通过css 添加标签 -->
</div>
<div class="bottom"></div>
</body>
4.清除浮动的方法 — ④ 双伪元素清除法
-
操作:
项目中使用,直接给标签加类即可清除浮动
5.清除浮动的方法 — ⑤ 给父元素设置overflow : hidden
操作: 1. 直接给父元素设置 overflow : hidden
特点: • 优点:方便
.top { //父元素
margin: 0 auto;
width: 1000px;
/* height: 300px; */
background-color: pink;
overflow: hidden;
}