以下 HTML/CSS 结果让我感到奇怪和出乎意料,我真的在寻找其解析方式背后的逻辑。
假设:
#nav {
list-style-type-none
}
#nav li {
display: inline;
}
/* make the LI's stack horizontally */
#nav li a {
display: block;
padding: 5px;
}
/* display as block to add padding */
<ul id="nav">
<li><a href="#">Home</a>
</li>
<li><a href="#">About us</a>
</li>
</ul>
这导致 <li>
因为 <a>
垂直堆叠(像 block 元素)的显示为 block 元素。但我想要 <li>
将水平堆叠,因为我将它们定义为内联元素。
<li>
的显示为内联,为什么 inner 元素 <a>
有影响吗?
最佳答案
发生这种情况是因为包裹在 block 级元素周围的内联元素被子 block 拆分为 block 级。这是 w3 规范中的引述:
When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) are broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes.
http://www.w3.org/TR/CSS2/visuren.html#block-boxes
如果您查看该链接,您会看到他们的“匿名框”图,该图将内联文本包装在一个 block 中,后面跟着一个 block 级元素(在他们的例子中,一个 <p>
) .因此,为了进一步解释,在上面的引述中,基本上他们是说内联框父级被带有显示的子级拆分为 block 级框: block 。
这有意义吗?
为了使其正常工作,您可以将 li 设置为 display:inline-block
为了您的方便,我复制了您的代码并进行了以下更改。
#nav {
list-style-type-none
}
#nav li {
display: inline-block;
}
/* make the LI's stack horizontally */
#nav li a {
display: block;
padding: 5px;
}
/* display as block to add padding */
<ul id="nav">
<li><a href="#">Home</a>
</li>
<li><a href="#">About us</a>
</li>
</ul>
关于html - 阻止 <a> 内联 <li> 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27413095/