background hide when I use “float: left” on

2019-08-14 04:44发布

See code, below code is my question ;).

HTML:

<div class="header">
    <ul>
        <li><a href="#">Domov</a></li>
        <li><a href="#">O nás</a></li>
        <li><a href="#">Služby</a></li>
        <li><a href="#">Kontakt</a></li>
    </ul>
</div>

CSS:

.header {
    width: 1000px;
    margin: auto;
    margin-top: 8px;
}

.header ul {
    list-style-type: none;
    background: #363b40;
}

.header ul li {
    float: left;
}

.header a {
    color: #a3a7a6;
    text-decoration: none;
}

My question is why DIV background hide when I add "float: left" to .header ul li. Any solution please?

标签: css html menu
2条回答
SAY GOODBYE
2楼-- · 2019-08-14 05:20

The reason this is occurring is because the ul is collapsing, as it doesn't have any defined dimensions. When you float the children elements, it takes them out of the flow of the document. The same thing happens when you set their position to absolute.

You have a few options..

Set overflow:hidden on the parent, forcing it to contain the children.

jsFiddle example

.header ul {
    overflow: hidden;
}

...or setting a defined height on the ul.

jsFiddle example

.header ul {
    height: 20px;
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-08-14 05:25

add the class clearfix to header and the following code to your css

.clearfix:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}
.clearfix {
  display: inline-block;
}

`

查看更多
登录 后发表回答