Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set height of parent of absolutely positioned element to grow/shrink with child

Tags:

html

css

so i have this:

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

styled like this:

#parent {
    width: 100%;
    padding: 10px;
}

#child {
    position: absolute;
    width: auto;
    left: 0px;
    right: 0px;
}

how can I set #parent to grow and shrink in height with #child.

I know that setting child to be absolutely positioned pulls it out of the regular flow so the parent element loses the ability to see the child's height, but is there any way I can clear it maybe like you would with a float?

like image 669
bimbom22 Avatar asked May 22 '11 04:05

bimbom22


People also ask

How do I fix position relative to parent?

To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element. This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.

How do you absolutely center an element within a parent?

To make it completely centered, we need to use 'transform: translateY(-50%)' to bring the element up by half of its height.

How do you position a child relative to a parent?

The one key thing to remember when trying to position a child div relative to it's parent is that the child should be given the CSS property position:absolute; and the parent set to either position:absolute; or position:relative;.

What positioning style is considered a special case of absolute position?

Fixed positioning is really just a specialized form of absolute positioning; elements with fixed positioning are fixed relative to the viewport/browser window rather than the containing element; even if the page is scrolled, they stay in exactly the same position inside the browser window.


1 Answers

In CSS the control always flows from top down, so the child's height can be controlled by the parent but not the other way round. You could use the following jquery to achieve what you're after though:

var resizeParent = function() {
  var child_height = $('#child').height();
  $('#parent').height(child_height);
};

$(window).resize(function() {
  resizeParent();
});

$document.ready(function() {
  resizeParent();
});
like image 134
Doug English Avatar answered Sep 23 '22 19:09

Doug English