Luke
Luke

Reputation: 3046

width auto problems for an element containing floated children

This weird behavior is driving me crazy. If I upload the page on the server, the first time I open it on chrome/safari I get this problem:

enter image description here

If i refresh it, or when I'm working on the page locally, no problems at all.

enter image description here

The nav simply doesn't expand its width: auto to fit all a floated elements.

This is the really simple code (I deleted not-related rules, but if it could be useful to know I'm using a webfont):

html:

<nav>
  <a href="#">button</a>
  <a href="#">button</a>
  <a href="#">button</a>
  <div class="clear"></div>
</nav>

css:

nav {
  position: absolute;
  top: 50%;
  margin-top: -17px;
  width: auto;
  height: 33px;
}

nav > a {
  box-sizing: border-box;
  display: block;
  float: left;
  padding: 11px 13px;
  height: 100%;
  border: 1px solid #7a7e7f;
}

div.clear {
  clear: both;
}

Upvotes: 0

Views: 103

Answers (1)

Daniel Riemer
Daniel Riemer

Reputation: 1021

Basically setting the width of the nav element to 100% does the trick. Here’s an optimized example:

HTML

<nav>
  <a href="#">button</a>
  <a href="#">button</a>
  <a href="#">button</a>
</nav>

CSS

nav {
  position: absolute;
  top: 50%;
  margin-top: -17px;
  width: 100%;
  overflow: hidden; /* Makes the clearing div obsolete */
}

nav > a {
  box-sizing: border-box;
  float: left;
  padding: 11px 13px;
  border: 1px solid #7a7e7f;
}

Check it out on Codepen: http://codepen.io/zitrusfrisch/pen/Jcirx

Upvotes: 1

Related Questions