Lesson 4
Positioning with CSS
Placing elements in various areas of the Web page.
Use the position property to position CSS elements. There are four main values that determine an element’s position:
Fixed
A fixed element remains in a certain area on the Web page, even when scrolling and resizing the window. You might use fixed-position to display important announcements.
The fixed value requires top, right, bottom, and left values. These four values dictate where the fixed element appears on the Web page. Let’s apply the class .fixedElement to a div
.fixedElement { position: fixed; bottom: 0; right: 0; width: 200px; height: 100%; background-color: grey; }
In this instance, the HTML element with the class fixedElement will appear as a sidebar on the right side of the screen. I used this example to represent something similar to the Facebook chat sidebar.
Static
The static value is default CSS value, but it’s good practice to learn about it. Elements with the static value have no defined position on the Web page. Another way to say this is to call it a not positioned element. On the other hand, fixed, relative, and absolute values do have defined positions on the Web page, and are therefore called positioned elements.
.staticElement { position: static; }
Relative
The relative value is similar to the static value, until you add some extra frills to the relative value. So, let’s say that you’ve got two div containers—both with the position: relative; rule. The second container positions itself relative to its parent container.
.relativeFirst { position: relative; } .relativeSecond { position: relative; top: -15px; left: 15px; background-color: grey; width: 50%; }
Absolute
The absolute value can sometimes be tricky. Absolute elements appear relative to the nearest positioned anchor. Think of the absolute value as it would apply to pepperoni on a pizza. Consider two divs with the class .pizza and .pepperoni. We’re going to position the div with a class of .pepperoni on top of the div with a class of .pizza. In other words, the position of .pepperoni is dependent on the .pizza position. In your CSS document, the rule for .pepperoni should immediately follow the rule for .pizza. (Remember, CSS code cascades downward, so rules are applied from the bottom up.)
.pizza { position: relative; width: 500px; height: 250px; } .pepperoni { position: absolute; top: 100px; right: 0; width: 200px; height: 200px; }
Back to Lesson 3: The Box
Forward to Lesson 5