1

I working on a website that has 2 elements side by side inside of a parent element (I'm using float:left and float:right to control their positioning), but the parent element won't show up unless I set it to position:absolute. I can't do that because I am making a footer at the bottom of the website, and the parent element will be at a variable height.

jsfiddle

HTML

<div id="wrapper">
    <div id="div1">div 1</div>
    <div id="div2">div 2</div>
</div>
<div class="clear"></div>
<div id="footer">this is a footer</div>

CSS:

#wrapper {
    background:blue;
    /* setting to position:absolute will make blue bg show up,
    but footer disappear */
    position:relative;
    width:150px;
}
.clear {
    clear:both;
}
#div1 {
    float:left;
    display:inline;
    padding:20px;
}
#div2 {
    float:right;
    display:inline;
    padding:20px;
}

Am I missing something??

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
gingin
  • 115
  • 3

1 Answers1

0

When elements are floated, they are essentially removed from the normal flow. Thus, if an element only contains floated elements (as in your case), the parent element will collapse upon itself and have a height of 0.

A common approach to work around this is to use a clearfix.

Example Here

#wrapper:after {
    content: '';
    clear: both;
    display: table;
}

or..

Example Here

#wrapper {
    background: blue;
    position: relative;
    width: 150px;
    overflow: auto;
}

Alternatively, you could set an explicit height on the element, too.


I just noticed that you had a .clear element in your example (<div class="clear"></div>). For it to work, it would have had to be inside of the element with floated children:

Example Here

<div id="wrapper">
    <div id="div1">div 1</div>
    <div id="div2">div 2</div>
    <div class="clear"></div>
</div>
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304