Valky
Valky

Reputation: 1866

Why a float right div is floating inside the next div?

I was hoping I wasn't a beginner with css, but I can't understand why the following happens...

You can see an example here

I wish to display 2 separated div on the same "line" :

So, I've done the following

// CSS
.div2 {
    background:#EDEDED;
    float:right;    
}
.div1  {    
    background:#CCC;
}
.div1, .div2 {
    padding:4px;
    margin:4px;
}
.round {
    -webkit-border-radius:8px;
    -moz-border-radius:8px;
    border-radius:8px;
    border:1px solid #000;
}
// HTML
<div class="div2 round">Test 2</div>
<div class="div1 round">Test 1</div>

But the .div2 is inside the first div... Bad display

How to display something like following ? (Like I thought it should be displayed...) Good display

Any help appreciated...

EDIT : SOLUTION By user570783

.div1 {overflow:hidden;}

Work like a charm, but not really documented, why this works ?

Upvotes: 1

Views: 163

Answers (2)

Thomas Hudspith-Tatham
Thomas Hudspith-Tatham

Reputation: 471

OK, there are many solutions here involving, floats, inline-block, margins and borders but all require knowledge of at least one element's size.

However!

There's a trick you can do here. If you add 'overflow:hidden' to the first div it will force the div to 'block formatting context'

This will get the result you're after, with dynamic sized right floating element.

To make this work in IE5 and 6 you need to trigger 'hasLayout' on the first element, so position: relative;

fiddle

Upvotes: 2

Cole Tobin
Cole Tobin

Reputation: 9426

float does what is says. float. as in stuff can be underneath it. Text will be wrapped, but borders won't

if you know the width of "Test 2", you can add a "margin-right: x;"

Upvotes: 2

Related Questions