CSS导航栏:UL之后的文字浮动 - 为什么?

时间:2013-03-25 19:10:13

标签: css

我正在玩这个网站的水平导航栏:

http://www.w3schools.com/css/tryit.asp?filename=trycss_float5

使用以下代码:

<head>
<style>
ul
{
     float:left;
     width:100%;
     padding:0;
     margin:0;
     list-style-type:none;
}
a
{
     float:left;
     width:6em;
     text-decoration:none;
     color:white;
     background-color:purple;
     padding:0.2em 0.6em;
     border-right:1px solid white;
}
a:hover {background-color:#ff3300;}
li {display:inline;}
</style>
</head>

<body>
<ul>
      <li><a href="#">Link one</a></li>
      <li><a href="#">Link two</a></li>
      <li><a href="#">Link three</a></li>
      <li><a href="#">Link four</a></li>
</ul>

<p>
      In the example above, we let the ul element and the a element float to the left.
      The li elements will be displayed as inline elements (no line break before or    after the element). This forces the list to be on one line.
      The ul element has a width of 100% and each hyperlink in the list has a width of 6em (6 times the size of the current font).
      We add some colors and borders to make it more fancy.
</p>

如果在ul的样式中,浮动被删除,那么p文本浮动在ul周围。但我的问题是浮点数应用于链接元素,而不是ul。那么为什么p如此贪婪地占据了ul的空白?

请帮助澄清。非常感激。

1 个答案:

答案 0 :(得分:1)

段落浮动在列表菜单旁边,因为UL不再占用100%的宽度,因为它的子链接是浮动的。

在段落上放置overflow:auto规则或者段落上的clear:left会产生类似的结果,其中段落不会浮动到列表旁边。

W3C wiki entry可能有助于理解:

  

如上所示,父框通常不会扩展为   包含漂浮的孩子。例如,这通常会引起混淆   当你做一个横向时,一个元素的所有子元素都浮动   通过浮动所有li元素从无序列表中选择菜单。以来   浮动的盒子从流动中取出并且不影响父母   框,浮动所有孩子有效地使父母空和   它会崩溃到零高度。有时候这是不可取的   实例,如果要在父级上设置背景。如果是父母   高度为零,没有背景可见。