03. Positioning an Element

There are three ways to position an element: absolute, relative and fixed.

Absolute

An element with absolute positioning is completely removed from the document flow. Thus, no other documents push it around, and you can move elements to exact locations on the screen.

To note the exact position of the element with a property of absolute, we set properties top, left, right or bottomto specify the position.

div.abs {
  position: absolute; 
  top: 10px;
  left: 10px;
}

The above code will take a div with class "abs" out of the flow and place it where it is exactly 10 pixels from the top and 10 pixels from the left.

Relative

You may place an object relative to where it's supposed to be. Again, you can use the top, left, right and bottom properties to specify its position.

div.rel {
  position: relative; 
  top: 10px;
  left: 10px;
}

The above code will place it 10 pixels down and 10 pixels to the right of where it's supposed to be.

Fixed Positioning

This will position an element relative to the viewport window. An example of this would be a navigation bar that stays up on the top of your screen. Even with the user scrolling down the page, a fixed element will keep its position.

div.fix {
  position: fixed;  
}

The element with class fix will stay in one position, no matter how the user scrolls.

Using z-index to specify element order

If boxes overlap, you may use the z-index property to control which element appears on the top. The higher z-index valued components will appear at the top.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Ad