简体   繁体   English

为什么在CSS中,display:inline只对“ li a {”有效,而对“ li {”无效?

[英]Why doesn't display:inline work for “li a {”, only “li {” in CSS?

I'm learning how to create menus as part of my first website build and came across a tutorial on horizontal vs. vertical. 我正在学习如何在我的第一个网站构建中创建菜单,并且遇到了水平与垂直教程。 It seems most of it comes down to defining your list as either "block" or "inline" in the CSS. 似乎大部分归结为将列表定义为CSS中的“阻止”或“内联”。 This makes sense to me, but what doesn't is why 这对我来说很有意义,但是为什么呢?

li a { 
  display:inline; 
}

doesn't create a horizontal menu. 不会创建水平菜单。 But doing 但是做

li {
  display:inline; 
} 

will create that horizontal menu. 将创建该水平菜单。 I'm guessing it has to do with something about the "li a" vs. just "li" elements. 我猜想这与“ li a”和“ li”元素有关。 For reference I have all of my list items as a link element. 作为参考,我将所有列表项都作为链接元素。 Code: 码:

HTML - HTML-

<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>

And CSS for vertical - 和CSS垂直-

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
}

li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}

The li element is by default display: list-item . li元素默认display: list-item The a element is by default display: inline . 默认情况下, a元素display: inline So changing the a 's display while not changing its parent does nothing. 因此,在不更改其父级的情况下更改a的显示不会产生任何作用。 It's kind of like expecting someone to notice that you've changed your shirt when you've only changed your undershirt. 这就像在期待别人注意到您只更换了汗衫时就已经换了衬衫。 So for a inline list, you need to make the li s inline. 因此,对于内联列表,您需要使li内联。 Making the a s block is optional, it just means you can mess around with the padding and/or margin and other properties that you can't change with inline elements. a s块是可选的,这仅意味着您可以乱用内联元素无法更改的填充和/或边距以及其他属性。

https://jsfiddle.net/ybkkgpoe/ https://jsfiddle.net/ybkkgpoe/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM