Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning a Child Div in a parent div [duplicate]

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.

like image 278
Johannes Avatar asked Sep 27 '11 05:09

Johannes


1 Answers

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.

like image 182
Kaivosukeltaja Avatar answered Nov 10 '22 14:11

Kaivosukeltaja