Stop Ignoring Each Other: Fixed vs Absolute

The CSS position properties allow elements to be visually presented and positioned quite accurately on screen. This is definitely a concept that’s easy to grab but hard to absorb. Some of these properties are ignored by the normal work flow and each other while some of them respect the CSS “gravity.” Recently a friend of mine is trying to have a fixed side bar on the left and the main content with absolute positioning to the sidebar’s right for her website. So I found a solution from the source code of this site.

To refresh my memories about the positioning properties, I’ve looked at the definitions for each of them (taken from http://www.w3schools.com):

Static Positioning: HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, and right properties.

Fixed Positioning: An element with fixed position is positioned relative to the browser window. It will not move even if the window is scrolled. Fixed positioned elements are removed from the normal flow. The document and other elements behave like the fixed positioned element does not exist. Fixed positioned elements can overlap other elements.

Relative Positioning: A relative positioned element is positioned relative to its normal position. The content of a relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow.

Absolute Positioning: An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>.

My example will contain the following in HTML:


<div id="sidebar">Fixed Position Sidebar</div>
<div id="content">Absolute Position Content</div>


Since both fixed and absolute positioning will ignore each other, the result of having both of them present will be a problem when the browser window is re-sized to be smaller than the whole visible area. If you scroll the horizontal bar at the bottom of the browser after it is decreased in view size, the div with absolute position will move left and right overlapping with the div with fixed position.

The quick fix is to implement jQuery and add the following script:


$(function(){
	var wrap = $('<div>').css({
	width: $('#sidebar').width(),
	height: $('#sidebar').height()
	});
	$('#sidebar').wrap(wrap);
	$(window).scroll(function() {
	$('#sidebar').css('left', $(window).scrollLeft()*-1);
	});
});



Demo 1 and Demo 2 are showing results of before and after the script is implemented:
DEMO 1 (Before) DEMO 2 (After)