If you’re new to designing with CSS layout, it’s simple to get started with these six positioning properties:
There are more positioning properties, but we’ll begin with these most practical ones.
To begin, here are two divs with very simple CSS rules. None of the special positioning properties have been applied yet (click on this image or any image below to view the live page.) We’ll call these the “simple” divs.
We’re using simple HTML too:
The z-index CSS property identifies how “close” or “far away” a CSS layer is from the viewer. In other words, width goes in one dimension horizontally, height adds a second dimension vertically, and z-index adds a third dimension on an axis perpendicular to the screen. This is useful when divs overlap. The lower the z-index (e.g. z-index: 1;), the further back a div is. The higher it is (e.g. z-index: 99;), the more forward it is. This technique requires that you set the position to relative (we’ll look at position in greater detail later.)
Below, I’ve adjusted the margins of the second div so that the two boxes overlap. The purple box has a z-index of 1, putting it behind the orange box which has a higher z-index of 2. Both have a position of relative.
Here’s what happens if we switch the z-index values of the two boxes: the purple box moves to the front.
The position CSS property can be either set to static, relative, absolute, fixed. The default position is static.
- Static divs get plunked down right where they are in the flow of the HTML.
- Relative divs are like static divs but can be moved relative to the previous content.
- Absolute divs get pulled out of the HTML flow and act independently of all other divs.
- Fixed divs work like absolute divs with a twist: they stay in the same place in the browser window even when you scroll down.
We’ve looked at an application of the relative position above. Let’s go back to our simple divs and add absolute positions instead. Both divs are now positioned relative to top-left of the browser window instead of relative to each other.
A div with a fixed position stays in one place as you scroll.
Next: 3. Float