当我为 UL 设置背景图像时,为什么在子元素已经设置了宽度和高度时还必须设置这些设置?
我正在学习有关使用 CSS 创建按钮的教程。
按钮的背景在 UL 元素中设置。我注意到,如果删除 UL 元素的高度和宽度属性,背景图像就会消失,就好像 UL 大小变为零一样。从盒子模型的角度来看,这对我来说没有意义。子元素( LI )已设置尺寸,并且应相应地拉伸 UL 的尺寸。有人能解释一下发生了什么事吗?
ul {
list-style-type: none;
background-image: url(navi_bg.png);
height: 80px;
width: 663px;
margin: auto;
}
I'm following this tutorial on creating buttons with CSS.
http://www.secondpicture.com/tutorials/web_design/css_ul_li_horizontal_css_menu.html
The background for the buttons is set in the UL element. What I've noticed is if I remove the height and width attributes of the UL element the background image disappears as if the UL size goes to zero. This doesn't make sense to me from a box model perspective. The children elements( LI ) have set dimensions and should be stretching out the size of the UL accordingly. Can someone explain what is going on?
ul {
list-style-type: none;
background-image: url(navi_bg.png);
height: 80px;
width: 663px;
margin: auto;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是浮动的,因此它们会从文档流中删除,从而导致
折叠。
为了达到您预期的效果,请尝试将
float: left;
添加到中。
The
<li>
s are floated so they are removed from the document flow which is causing the<ul>
to collapse.To behave like you expect, try adding
float: left;
to the<ul>
as well.根据教程,LI 是 float: left,这导致它们不再占用父元素 (UL) 中的空间。您需要一个clearfix来解决此问题,请参阅此线程:“clearfix”的哪些方法可以我用?
According to the tutorial, the LIs are float: left, which causes them to no longer take up space in the parent element (UL). You need a clearfix to resolve this issue, see this thread: What methods of ‘clearfix’ can I use?
我经常使用的一个很好的解决方法是将
放入
中,例如
,然后将背景图像应用到
元素。
更好的答案:
在 CSS 中,将
display: table-row;
添加到ul
元素,并将display: table-cell;
添加到li
元素。这比float: left
更好,因为它不会折叠您的父元素,而display: inline-block
因为它不会在项目之间呈现令人讨厌的间隙。A good fix that I always use is putting the
<ul>
in a<div>
as such<div id="nav"><ul>...</ul></div>
and then applying the background image to the<div>
element.Better answer:
In your CSS add
display: table-row;
to theul
element anddisplay: table-cell;
to theli
elements. This is better thanfloat: left
since it doesn't collapse your parent element anddisplay: inline-block
since it doesn't present that annoying gap between items.