CSS: the auto value of the top property: a singularity

CSS: the auto value of the top property: a singularity

A peculiar feature of CSS positioning.

The CSS top property has a unique feature when it interacts with other static elements: if set to auto, the positioned element will be placed just after the first non-positioned element that precedes the positioned element in the document tree. This is an interesting feature, especially when we can't know in advance the height of static elements.

Consider the following markup:


<header>
	Header
</header>
<nav>
	<a href="#">Lorem</a>
	<a href="#">Ipsum</a>
	<a href="#">Dolor</a>
</nav>

If our header has the following styles:


header {
	height: 3em;
	line-height: 3;
	text-align: center;
	background: #ccc;
}

we should specify top: 3em in order to position the navigation menu after the header. This is not necessary with top: auto because our header is a static element and precedes the navigation menu in the document tree:


nav {
	width: 100%;
	height: 3em;
	line-height: 3;
	position: absolute;
	top: auto;
	left: 0;
	background: #333;
}

A final consideration: if we don't specify a stated width on absolutely positioned elements, then the shrink-to-fit algorithm will be applied by browsers. This particular algorithm, introduced in CSS 2.1, makes an element to be as wide as its contents, nothing less, nothing more.

[view-example url="http://codepen.io/gabrieleromanato/pen/qjFKc"]