学海无涯,回头是岸
不务正业
极简老人

方法一:

html:

<div id="all1">

<div id="left1">1</div>

<div id="left2">1</div>

<div style=" clear:both; "></div>

</div>

css:

#left1{ float:left;width:200px;}

#left2{ float:left;width:200px;}

#all1{}

这个方法的关键在于用了clear:both来清除了浮动元素,把父元素all1撑开。

方法二:

html:

<div class="aa">
  <div class="bb">sffsssssssssssss</div>
  <div class="cc">sffss</div>
</div>

css:

.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}
.bb { border:1px solid #f00; background:#999; float:left;}
.cc{ border:1px solid #f00; background:#999; float:left;}

此方法的重点在于,子元素有float之后,父元素需要设置一个overflow:hidden;,这样就可以自动撑开父元素aa。

 

特别注释:

 

overflow:hidden要有宽度或者高度才会溢出部分隐藏,如果外部盒子没有宽度或者高度,里面又是浮动元素,就会被撑开

 

总结如上的方法,各有适合的地方。比如overflow:hidden之后,超出父元素位置的子元素就看不到了,可以试一下如下的两段代码对比一下,

代码一:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<style type="text/css" >
.aa{ border:1px solid #000; background:#CC4;overflow:hidden;}
.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}
.cc{ border:1px solid #f00; background:#999; float:left;}
</style>
<body>
<div class="aa">
  <div class="bb">图片</div>
  <div class="cc">图片</div>
</div>
</body>
</html>

 

效果图:

代码二:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<style type="text/css" >
.aa{ border:1px solid #000; background:#CC4;}
.bb { border:1px solid #f00; background:#999; float:left; margin-top:-10px;margin-left:110px;}
.cc{ border:1px solid #f00; background:#999; float:left;}
</style>
<body>
<div class="aa">
  <div class="bb">图片</div>
  <div class="cc">图片</div>
<div style="clear:both"></div>
</div>
</body>
</html>

效果图:

 

posted on 2016-06-04 20:41  MirageFireFox  阅读(3227)  评论(0编辑  收藏  举报