浮动元素
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>浮动元素</title>
<style>
#container1 {
width: 400px;
height: 50px;
background-color: lightgrey;
border: 1px solid;
}
#container1 div {
width: 100px;
height: 30px;
border: 1px solid;
background-color: #fff;
}
.lft {
float: left;
}
.rgh {
float: right;
}
#container2 {
width: 400px;
height: 100px;
background-color: lightgrey;
border: 1px solid;
}
#container2 .lft {
width: 300px;
height: 20px;
border: 1px solid;
background-color: #fff;
}
#container2 .rgh {
width: 150px;
height: 50px;
border: 1px solid;
background-color: #fff;
}
#container3 {
width: 400px;
height: 150px;
background-color: lightgrey;
border: 1px solid;
}
#container3 div {
border: 1px solid;
background-color: #fff;
}
#container3 div:nth-child(-n+2) {
width: 100px;
height: 30px;
}
.clr {
clear: both;
}
#container3 div:nth-child(4) {
width: 190px;
height: 40px;
}
#container3 div:nth-child(5) {
width: 120px;
height: 20px;
}
#container3 div:nth-child(n+7) {
width: 120px;
height: 20px;
}
</style>
</head>
<body>
<h2>只要宽度之和小于父元素宽度,块级元素就在同一行</h2>
<div id="container1">
<div class="lft">float left;</div>
<div class="lft">float left;</div>
<div class="rgh">float right;</div>
</div>
<h2>两个浮动元素宽度之和大于父元素宽度,其中一个换行</h2>
<div id="container2">
<div class="lft">float:left</div>
<div class="rgh">float:right</div>
</div>
<h2>使用clear:both清除浮动并创建新的浮动行</h2>
<div id="container3">
<div class="lft">float left;</div>
<div class="lft">float left;</div>
<div class="clr"></div>
<div class="lft">float left;</div>
<div class="rgh">float:right</div>
<div class="clr"></div>
<div class="rgh">float:right</div>
<div class="rgh">float:right</div>
<div class="rgh">float:right</div>
</div>
</body>
</html>
页面效果