The Two Ways of Sizing Absolute Elements in CSS

    Craig Buckler
    Share

    Absolute SizingAnyone who has used CSS for a while will know about the merits of absolute and relative positioning. To recap:

    position: relative allows an element to be shifted from its original position either horizontally (using left or right) or vertically (using top or bottom).

    position: absolute allows an element to be positioned with respect to a containing block using left, right, top or bottom (the containing block is the nearest ancestor node with a position of relative, absolute or fixed).

    Positioning nodes is therefore straightforward, e.g.

    HTML:

    
    <div id="outer">
    	<div id="inner"></div>
    </div>
    

    CSS:

    
    #outer
    {
    	position: relative;
    	width: 200px;
    	height: 200px;
    	margin: 20px auto;
    	border: 2px solid #c00;
    }
    
    #inner
    {
    	position: absolute;
    	left: 50px;
    	top: 50px;
    	width: 96px;
    	height: 96px;
    	background-color: #ddc;
    	border: 2px solid #00c;
    }
    

    (The actual width and height of the inner block will be 100px owing to the addition of the border).

    The following boxes are rendered in every modern browser (including IE6):

     

    Less well known is that you can apply all the left, right, top and bottom properties at the same time. The following CSS will render the inner element identically:

    
    #inner
    {
    	position: absolute;
    	left: 50px;
    	right: 50px;
    	top: 50px;
    	bottom: 50px;
    	background-color: #ddc;
    	border: 2px solid #00c;
    }
    

    The width and height of the inner box will remain 100px, but we do not need to need to explicitly set the dimensions.

    This could be useful when:

    • the spacing around the element is more critical than the width or height. You can also use negative left, right, top and/or bottom properties to make the inner box larger than its outer parent.
    • you have multiple inner elements with differing borders and padding but need consistent outer spacing. This method allows you to create a single style for all those elements.

    JavaScript animations can also benefit since it can be easier and quicker to resize an element if you do not need to calculate the resulting width and height, e.g.

    
    // expands and contracts the inner box
    window.onload = function() {
    
    	var inner = document.getElementById("inner");
    	var offset = 100, dir = -1;
    	setInterval(function() {
    		inner.style.left = inner.style.right = inner.style.top = inner.style.bottom = offset+"px";
    		offset += dir;
    		if (offset == 0 || offset == 100) dir = -dir;
    	}, 10);
    	
    }
    

    A note about browser compatibility: this technique works in all the main browsers, except IE6 which only understands explicit widths and heights. There’s a surprise!