问题
Please refer to the following code:
<!DOCTYPE html>
<html>
<head>
<style>
ul {
border: 1px solid red;
list-style-type: none;
margin: 0;
padding: 0;
/*overflow: hidden;*/ /* Remove this comments */
background: yellow;
}
li {
border: 1px solid red;
float: left;
}
li a {
display: block; /* what is this used for here? */
color: black;
text-align: center;
padding: 16px;
text-decoration: none;
}
li a:hover {
background-color:red;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
I would like to know why list height is zero, even though there are list elements in it?
If you comment in overflow:hidden in the css, then the list gets a proper height other than zero. Can you tell the reason?
回答1:
The height of your ul
is zero because you're floating your child elements which, in essence, removes them from the layout of the containing list.
If you also float your ul
, you'll see that it contains your child li
elements and the height sizes itself as I believe that you're looking for it to do.
There is some further context on how float
impacts page flow here, if you're curious.
来源:https://stackoverflow.com/questions/48843680/ul-height-is-0-in-this-code-why-it-has-to-do-with-overflowhidden