Relative parent DIV to inherit the width of absolute child DIV

With modern CSS, this is doable.

HTML:

<div id="parent">
    <h3>Top Aligned Title</h3>
    <div id="child">
        <p>CHILD ELEMENT</p>
    </div>
</div>

CSS:

#parent {
    background:red;
    height: 500px;
    position:relative;
}
#child {
    background:green;
    position: absolute;
    top:100%;
    -webkit-transform: translateY(-100%);
    -ms-transform: translateY(-100%);
    transform: translateY(-100%);
    width: 100px;
}

http://jsfiddle.net/Bushwazi/bpe5s6x3/

  1. transform:translateY(-100%); is the trick. It's math is based on the element's box-model.
  2. You could also combine top:50%; with transform:translateY(-50%); to center it.
  3. You can swap top for left and translateY for translateX to position the element horizontally.

The short answer is that what you are asking basically can't be done with pure CSS / HTML. (at least without tables) You'd need Javascript that would read #child's width/height and then do the calculation you want to do (I don't know) and set a new height/width to #parent.

Otherwise, if you mean that you want #child's height/width to change according to its content, of course this is native CSS, just set it's height/width to auto and then start adding text inside it you'll see it will start growing to fit your content inside.

As the #child is positioned absolute, then it is taken OUT of the normal flow of the document, therefore it will not affect the #parent.

Tags:

Css