CSS--浮动(float)布局

浮动概述:浮动,指的是元素标签使用float属性。应用float属性的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。浮动的本质是让文字围绕图片,但现在很多时候使用浮动进行布局。但使用float属性进行布局也会带来一些问题,下面举例说明。

1.使用float进行布局但需要clear的实例:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>DIV布局--float属性</title> 
</head>
<body>

<div id="container" style="500px">

<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;text-align:center;">主要的网页标题</h1></div>

<div id="menu" style="background-color:#FFD700;height:200px;100px;float:left;">
<b>菜单</b><br>
HTML<br>
CSS<br>
JavaScript</div>

<div id="content" style="background-color:#EEEEEE;height:200px;400px;float:left;">
内容在这里</div>

<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
版权 © runoob.com</div>

</div>
 
</body>
</html>

 

2.使用float布局但不进行clear的实例:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>DIV布局--float属性</title> 
</head>
<body>

<div id="container" style="500px">

<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;text-align:center;">主要的网页标题</h1></div>

<div id="menu" style="background-color:#FFD700;height:200px;100px;float:left;">
<b>菜单</b><br>
HTML<br>
CSS<br>
JavaScript</div>

<div id="content" style="background-color:#EEEEEE;height:200px;400px;float:left;">
内容在这里</div>

<div id="footer" style="background-color:#FFA500;text-align:center;">
版权 © runoob.com</div>

</div>
 
</body>
</html>

3.分析:

事实上这两段代码并没有什么不同,只是在最后的一个div中少了“clear:both”,少了清理操作。由于浮动的框不在普通文档流中(与position:absolute不同,虽然两者都使元素脱离文档流,但使用float属性的元素还会在文档流中占据一个位置),没有进行清理操作,最后一个div#footer块框将div#menu与div#content当成不存在

一样。所以它的高度等于200px+21px=221px。再截个图对比就可以看得更明显了:

4.对浮动(float)更加深入细致的研究可以参考下面的资料,而且目前还存在一个问题,为什么文字环绕float的图片而不被覆盖呢?这里貌似可以找到答案。

https://www.zhangxinxu.com/wordpress/2010/01/css-float%e6%b5%ae%e5%8a%a8%e7%9a%84%e6%b7%b1%e5%85%a5%e7%a0%94%e7%a9%b6%e3%80%81%e8%af%a6%e8%a7%a3%e5%8f%8a%e6%8b%93%e5%b1%95%e4%b8%80/

https://www.zhangxinxu.com/wordpress/2010/01/css-float%e6%b5%ae%e5%8a%a8%e7%9a%84%e6%b7%b1%e5%85%a5%e7%a0%94%e7%a9%b6%e3%80%81%e8%af%a6%e8%a7%a3%e5%8f%8a%e6%8b%93%e5%b1%95%e4%ba%8c/

原文地址:https://www.cnblogs.com/kuai-man/p/10675654.html