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?
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.
To make it completely centered, we need to use 'transform: translateY(-50%)' to bring the element up by half of its height.
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;.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With