Extend Height To Include Absolutely Positioned Children
I'm building an html/javascript theme designer for a CMS. Elements are positioned absolutely and can be moved/resized via the mouse, and/or contain editable text whose height may
Solution 1:
I found a pure-css solution! In summary:
- Set the child elements to position: relative instead of absolute.
- Set their margin-right to be their negative width, to give them zero effective width, and make them float: left to keep them all on the same line. This makes all of them have an origin of 0, 0.
- Then we can set their left and margin-top properties to position them absolutely within their parents. Note that margin-top is required instead of top because top won't push down the bottom of the parent element.
JSFiddle here or code below:
<style>div.layer { position: relative; float: left; }
div.layer1 { width: 400px; border: 1px solid black }
div.layer2 { margin-top: 20px; left: 100px; width: 100px; margin-right: -100px; border: 1px solid blue }
div.layer3 { margin-top: 30px; left: 170px; width: 100px; margin-right: -100px; border: 1px solid red }
div.layer4 { margin-top: 30px; left: 20px; width: 60px; margin-right: -60px; border: 1px solid green }
</style><divclass="layer layer1"style="position: relative; display: block; width: 400px; border: 1px solid black;">
Container
<divclass="layer layer2"contentEditable>Edit me</div><divclass="layer layer3"><divclass="layer layer4"contentEditable>Edit me</div></div></div>
Solution 2:
absolute positioned elements are removed from the flow, thus ignored by other elements
the only way you have is to set the child position to position:relative, in this way it is possible to move it using right,left,top and bottom and also change parent display to display:inline-block
Solution 3:
If you want keep the children absolutely positioned, you can use the following script to resize the container : http://jsfiddle.net/6csrV/7/
var layer1 = document.getElementsByClassName('layer1'),
i = 0, len = layer1.length, childHeight;
for(; i < len; i++) {
childHeight = layer1[i].getElementsByClassName('layer')[0].clientHeight;
layer1[i].style.height = childHeight + 'px';
}
document.addEventListener('keyup', function(e) {
if(e.target.className.indexOf('layer2') !== false) {
e.target.parentNode.style.height = e.target.clientHeight + 'px';
}
});
Post a Comment for "Extend Height To Include Absolutely Positioned Children"