11

Possible Duplicate:
Make outer div be automaticly the same height as its floating content

I feel like I'm missing something very simple here...

We have a simple setup: a parent div that contains a child div. I want to:

  • make the parent resize its height based on the child
  • align the child to the right edge of the parent instead of the default left.

Using float:right will cause the parent to no longer resize correctly and the child to 'jump out' of the parent.

I've tried using align: right and text-align: right but so far no dice.

HTML:

    <div id="parent"> <p>parent</p>
        <div class="child"> <p>child</p> </div>

        <div class="child right"> <p>child2</p> </div>
    </div>

CSS:

    div{ padding: 15px; margin: 5px; }
    p{ padding: 0; margin: 0; }

    #parent{
        background-color: orange;
        width: 500px;
    }

    .child{
        background-color: grey;
        height: 200px;
        width: 100px;
    }

    .right{ float: right; } // note: as the commenters suggested I should also be using a float:left on the other child.

Result:

result

What I want:

what I want

Any suggestions on what I could change either with #parent or .right to make child2 align to the right properly?

EDIT

The best fix I found for this is just using display:table on the parent. Though I haven't tested this in IE it fixes the issue in the browsers I care for and avoids using the un-intuitive overflow:hidden method discussed in the comments.

Even better: set margin-left of the child to auto.

Community
  • 1
  • 1
Johannes
  • 6,232
  • 9
  • 43
  • 59

1 Answers1

9

Try floating the contents and adding overflow: hidden to the parent. It's counter-intuitive but worked for me with a similar issue.

EDIT: Also float the first child to the left.

Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
  • you could also use float:left on .child and float:right on .child + .child – albert Sep 27 '11 at 05:35
  • 1
    What the... You're correct, adding overflow:hidden to the parent makes floated divs once again be encompassed by the parent div. This is incredibly counter-intuitive... – Johannes Sep 27 '11 at 05:37
  • Would there happen to be an alternative that doesn't use overflow:hidden? unfortunately in the actual project I wanted this for I have a `position:relative` div that overlaps the parent which now gets cut off. – Johannes Sep 27 '11 at 05:44
  • I figured out a way without using `overflow`. I just had to add `display:table` to the parent. – Johannes Sep 27 '11 at 05:58