1

Fiddle here: http://jsfiddle.net/csaltyj/mbnWm/

<style type="text/css">
    #container {
        border: 2px solid #000;
        position: absolute;
        width: 20em;
    }

    .box {
        background: transparent;
        position: absolute;
        border: 1px solid #0f0;
    }
</style>
<div id="container">
    <div class="box">
        <p>X</p>
        <p>Taller than the other two.</p>
    </div>
    <div class="box">
        <p>&nbsp;&nbsp;&nbsp;Y</p>
    </div>
    <div class="box">
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Z</p>
    </div>
</div>

This is not working. They overlap fine, but there are issues. The goal is to:

  1. Get the #container to properly wrap around the children divs.
  2. Have the .box divs fill (width & height) the parent #container (so the green borders should reach all the way out to the thick black border).

This must be possible, I'm just having a hard time with positioning. (that and floats seem to be the toughest parts of CSS)

Thanks for any help.

kapa
  • 77,694
  • 21
  • 158
  • 175
CaptSaltyJack
  • 15,283
  • 17
  • 70
  • 99

2 Answers2

2

How to make children auto fit parent's width only with CSS?

Community
  • 1
  • 1
Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
2

The problem you have here is that anything that is position: absolute; is removed from flow. Thus, #container can never contain the .boxes. In this cause you will need to set height and width on #container and make sure the .boxes can never expand beyond it. You requested they fill the #container, so I've done that here: http://jsfiddle.net/X3EJ6/

Note though that because width and height are set to 100% the borders will not work correctly. You will need to set explicit values or use box-sizing and set it to border-box (this is not support in IE < 8).

<style type="text/css">
    #container {
        border: 2px solid #000;
        position: absolute;
        width: 20em;
        height: 10ex;
        overflow: hidden;
    }

    .box {
        background: transparent;
        position: absolute;
        border: 1px solid #0f0;
        width: 100%;
        height: 100%;
    }
</style>
<div id="container">
    <div class="box">
        <p>X</p>
        <p>Taller than the other two.</p>
    </div>
    <div class="box">
        <p>&nbsp;&nbsp;&nbsp;Y</p>
    </div>
    <div class="box">
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Z</p>
    </div>
</div>
Kevin Peno
  • 9,107
  • 1
  • 33
  • 56
  • Very nice. Of course, I forgot to mention that I need to not specify a height on anything at all. So I've modified your code and used jQuery to dynamically set the heights to all match the largest item in the container. http://jsfiddle.net/csaltyj/X3EJ6/1/ – CaptSaltyJack May 06 '11 at 18:31
  • 1
    @CaptSaltyJack, same issue exists if you want borders to appear inside the parent. You will need to subtract any padding, borders, and margins on `.box` from the `innerWidth` of `#container` – Kevin Peno May 06 '11 at 18:46