1

Why aren't these two elements next to each other?

Demo

HTML

<div> 
    <p>I'm a paragraph and I'm on the left!!!</p> 
    <h3>I'm a header and I'm on the right</h3> 
</div>

CSS

div p{
    float: left;
    width:30%;
    border: 1px solid blue;
}

div h3{
    clear: both;
    float:left;
    width:10%;
    border: 1px solid red;
}

I thought by giving the h3 a clear: both would use the empty space next to the p.

But it didn't work. Can anyone explain why?

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Bosiwow
  • 2,025
  • 3
  • 28
  • 46

3 Answers3

1

They aren't next to each other because you disabled any floating left of h3 with clear:both. Remove that and they will. Like so http://jsfiddle.net/vHph8/

Klemen Tusar
  • 9,261
  • 4
  • 31
  • 28
1

Using clear: both; will clear the floats and will render the element below, inorder to make that work, you need to take out clear: both; from div h3 selector.

Also, if you want to float the header to the right you need to use float: right; rather using left.

This is what the clear: both; does to your example, it kinda acts like a wall between two floated elements.

enter image description here

Also this answer of mine will help you to understand how floats really work and the other one will help you understand clear both.


clear: both; is to clear the floated elements, so in your code, you should create a snippet of something like

.clear:after {
    clear: both;
    content: "";
    display: table;
}

And now use the above snippet on your container element which will self clear the element like, rest stays the same but as I said you need to remove clear: both; from div h3

<div class="clear"> 
    <p>I'm a paragraph and I'm on the left!!!</p> 
    <h3>I'm a header and I'm on the right</h3> 
</div>

What will happen if I don't clear the floats?

Well, say you have a background applied to the parent element, the color won't render at all, see it yourself...

Demo 1 (floats aren't cleared so you don't see the red background)

Demo 2 (floats are cleared, you can see a red background now)


It's not just about the background-color, if you have third element, than it will just sit beside the other two, so inorder to prevent that, we use clear: both; as well. I've covered these aspects in the answers I provided the link for.

Community
  • 1
  • 1
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
1

The css clear property resets the floating and actually causes the layout to proceed beneath all floating material.

if you delete it from your css, it works (jsfiddle: here).

collapsar
  • 17,010
  • 4
  • 35
  • 61