简体   繁体   中英

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. 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. For reference I have all of my list items as a link element. Code:

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 -

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 . The a element is by default display: inline . So changing the a 's display while not changing its parent does nothing. 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. 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.

https://jsfiddle.net/ybkkgpoe/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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