Positioning with CSS

To really make your page appear how you want it to, you need to specify the layout in high precision. There are a number of CSS properties which together allow for nearly any conceivable layout.

We’ll start with positioning and dimension CSS properties. First there are the four properties “left”, “top”, “right”, and “bottom”. Typically, you will use only two of these at a time, specifying “left” and “top” for example. You can specify the position in pixels or percent:

                    	
div#myDiv {
	left: 200px;
	top: 150px;
}

div#myOtherDiv {
	left: 20%;
	top: 10%;
}
						
					

The dimension properties include “height” and “width”. They can also be specified in either pixels or percent.

	
div#myDiv {
	left: 200px;
	top: 150px;
	width: 300px;
	height: 150px;
}

div#myOtherDiv {
	left: 20%;
	top: 10%;
	width: 20%;
	height: 10%;
}
	

There is also the idea of depth, or something like it, in that elements can be layered on top of one another using the “z-index” property. The z-index is a positive integer, and elements with higher z-index values will appear in front of or on top of elements with lower z-index values.

A key component of how your element is positioned is based on the “position” property. When the “position” is not set, it is in fact automatically set to “static”. This is the default behavior, and it means that the item is rendered as it normally flows on the page, regardless of the “top” and “left” properties. Setting position to “relative” allows for positioning of the element relative to other elements; this is one of the settings that makes the “top”, “left”, “right”, and “bottom” properties work as you’d expect.

When you want an item positioned precisely at one spot on the page, regardless of where other elements are, you want to set position to “absolute”. This will position the element offset from its parent relative/absolute element at precisely the location you specify. This allows you to specify a “left” property of “500px” and a “top” property of “200px” and have your element appear precisely at that point on the page, relative to its parent relative/absolute position element. If it does not have a parent element that is relatively or absolutely positioned, it will be relative to the browser tab’s viewport itself.

The last positioning setting is “fixed”. This can be incredibly useful for achieving some cool effects, when it’s used sparingly. An element with “fixed” positioning is tacked onto the screen at a specific location, and doesn’t move, even if you scroll the page. If you have a menu at the top of the screen that you want to always be in place, using “position: fixed” is the easiest way to do that - though it’s worth noting that some mobile devices don’t honor the “position: fixed” CSS rule, due to differences in how they render pages.