为什么需要浮动
什么是浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.one,
.two {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
.two {
float: right;
}
</style>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
</html>
浮动特性(重难点)
1浮动元素会脱离标准流(脱标)
视频:https://www.bilibili.com/video/BV1pE411q7FU?p=173
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.one {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
.two {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="one">浮动</div>
<div class="two">标准流</div>
</body>
</html>
2.浮动的元素会一行内显示并且元素顶部对齐
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 300px;
height: 300px;
float: left;
background-color: blue;
}
.two,
.four {
background-color: red;
}
.two {
height: 400px;
}
</style>
</head>
<body>
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
</body>
</html>
3.浮动元素会具有行内块元素特性
视频:https://www.bilibili.com/video/BV1pE411q7FU?p=175&spm_id_from=pageDriver
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
div {
height: 200px;
background-color: red;
float: right;
}
</style>
</head>
<body>
<span></span>
<div>111111</div>
</body>
</html>
浮动元素经常和标准流父级搭配使用
视频:https://www.bilibili.com/video/BV1pE411q7FU?p=176
解决这样的布局。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 600px;
height: 100px;
background-color: rgb(134, 115, 115);
margin: 100px auto;
}
.father div {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}
</style>
</head>
<body>
<div class="father">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
</html>
效果图