Introduction to Advanced Positioning in CSS

Welcome, future web designers! We're venturing into the domain of CSS Positioning, navigating through Static, Relative, Absolute, and Fixed types. Next, we'll adjust the positioning of our HTML elements using top, right, bottom, and left properties. Finally, we'll touch on the width and z-index properties.

Understanding Static Positioning

By default, all HTML elements have a static position. They flow naturally on the webpage, like stars in the sky. Static positioning disregards top, right, bottom, and left values. Let's observe a static paragraph:

<p style="position: static;">
  I stay put, like a steadfast star!
</p>
Delving into Relative Positioning

Next, let's implement some flexibility with relative positioning. This allows us to slightly shift HTML elements without impacting others. For this, top, right, bottom, and left properties come into play. In this example, our paragraph shifts 20 pixels to the right:

<p style="position: relative; left: 20px;">
  I'm a moving star, nudged right by 20 pixels!
</p>
<p style="position: relative; top: 10px;">
  And I am moved to the bottom by 10 pixels!
</p>
<p style="position: relative; bottom: 15px; right: 17px;">
  Another paragraph that is moved towards the top and left so that the gap from bottom is 15 pixels and the gap from right is 17 pixels;
</p>
Mastering Absolute Positioning

With absolute positioning, we allow our elements the freedom to roam. An element moves relative to the nearest positioned parent. If there are no such parents, it moves relative to the page. Here's an p element in the top-right:

<p style="position: absolute; top: 20px; left: 20px;">
  I'm a paragraph positioned absolutely at the top-left corner! Distance from top edge is 20px, and from left edge is also 20px.
</p>
Revealing the Power of Fixed Positioning

fixed positioning locks an element in a position relative to the viewport, which means the visible part of the web page on your screen. This technique ensures that the element remains in the same spot even when you scroll through the page. For example, in the following scenario, the header is kept at the top of the viewport at all times, providing a stationary point of reference as you move up and down the page:

<header style="position: fixed; top: 0;">
  Always at the top, like a guiding star!
</header>
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal