开发者

float:left for <li> creates spacing above navigation bar

Styling li tags with float:left is a standard way to create horizontal navigation bars. But whenever I do this, the entire navigation bar list gets separated from the containing div.

Removing float:left would fix the problem, but let's assume I want to do it this way.

HTML

<html>
<head>
  <link rel="stylesheet" type="text/css" href="temp.css" />
</head>
<body>
<div id="header">
  <h2>Demo: Navigation Bar</h2> 
  <ul id="navbar">
    <li>
      <a href="#">News</a>
    </li>
  </ul>
</div>
</body>
</html>

CSS

#header {
    margin: 10px;
    width: 8in;
    background-color: green;
    margin-left: auto; /* setting margin to auto centers block element */
    margin-right: auto; /* width must not be 100% */
}

#header ul { /* ul */
    list-style-type: none;
    padding: 0;
    margin-top: 0px;
}

#header li {
    display:block;
    float:left;
    background-color: silver;
    margin: 0;
}

Any insight is much appreciated!

Edit: Solution is to add empty div after the list, or style the containing div with overflow:hid开发者_如何学Goden.

After looking for an explanation why this happens, I found a great link explaining everything!

http://css-tricks.com/all-about-floats/


The trick is, working with float's - use clearfixes. In your case, add the following, before header closing tag </div>:

<div style="clear: both"></div>

That will make header strech, considering floating elements inside it.


Add a div after the ul with style clear:left; - I would go into more detail, but I'm on my iPad and about to go to bed.


Instead of anything in the li css code, put #header li{display: inline;} (and your color and other preferences)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜