清除浮动,我一般使用如下代码
/* 在浮动元素后加个div设置clear: both; height:0,overflow:hidden */
.clear {
clear: both;
height: 0px;
overflow: hidden;
}
但是这个div
放在什么位置是值得商榷的!
一般情形
注意清除浮动代码放置的位置,它与浮动元素同级。
代码
<!DOCTYPE html>
<html>
<head>
<title>清除浮动,使得父元素被撑开</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
.logo {
height: 80px;
background-color: #FFF;
}
.logo_right {
width: 200px;
height: 80px;
background-color: blue;
}
/* 在浮动元素后加个div设置clear: both; height:0,overflow:hidden */
.clear {
clear: both;
height: 0px;
overflow: hidden;
}
.wrap {
width: 100%;
height: 100px;
background-color: red;
}
.left {
width: 200px;
float: left;
height: 40px;
background: url(universe.jpg) no-repeat;
}
</style>
</head>
<body>
<div class="logo">
<div class="logo_right"></div>
<div class="clear"></div>
</div><!-- logo结束 -->
<div class="wrap">
<div class="left"></div>
</div>
</body>
</html>
效果图
div
中有img
元素
如果将清除浮动代码放置在与浮动元素同级,其效果图如下,发现它没有清除浮动
代码
<!DOCTYPE html>
<html>
<head>
<title>清除浮动,使得父元素被撑开</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
.logo {
height: 80px;
background-color: #FFF;
}
.logo_left {
float: left;
width: 200px;
}
.logo_left img {
width: 200px;
height: 80px;
}
.logo_right {
width: 200px;
height: 80px;
background-color: blue;
}
/* 在浮动元素后加个div设置clear: both; height:0,overflow:hidden */
.clear {
clear: both;
height: 0px;
overflow: hidden;
}
.wrap {
width: 100%;
height: 100px;
background-color: red;
}
.left {
width: 200px;
float: left;
height: 40px;
background: url(universe.jpg) no-repeat;
}
</style>
</head>
<body>
<div class="logo">
<div class="logo_left"><img src="future.png" alt="logo" /></div>
<div class="clear"></div>
</div><!-- logo结束 -->
<div class="wrap">
<div class="left"></div>
</div>
</body>
</html>
效果图
当浮动元素div
中有img
元素时,注意清除浮动代码放置的位置,它与浮动元素父级元素同级。
代码
<!DOCTYPE html>
<html>
<head>
<title>清除浮动,使得父元素被撑开</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
.logo {
height: 80px;
background-color: #FFF;
}
.logo_left {
float: left;
width: 200px;
}
.logo_left img {
width: 200px;
height: 80px;
}
/* 在浮动元素后加个div设置clear: both; height:0,overflow:hidden */
.clear {
clear: both;
height: 0px;
overflow: hidden;
}
.wrap {
width: 100%;
height: 100px;
background-color: red;
}
.left {
width: 200px;
float: left;
height: 40px;
background: url(universe.jpg) no-repeat;
}
</style>
</head>
<body>
<div class="logo">
<!-- 浮动元素中有img-->
<div class="logo_left"><img src="future.png" alt="logo" /></div>
</div><!-- logo结束 -->
<div class="clear"></div>
<div class="wrap">
<div class="left"></div>
</div>
</body>
</html>
效果图
TODO
目前还不太清楚,当清除浮动代码放置到与浮动元素(浮动元素含有img)同级时,不能清除浮动的原因。目前建议将清除浮动代码放到与浮动元素的父级元素同级。