CSS Position Properties Cheat Sheet

Front-end developers have all been there. Positioning elements in CSS still pains most of us, but once we get hold of its basics with some real-life examples, everything starts to make sense.

Positioning allows us to take elements out of the normal document flow and make them behave differently. This CSS Position Properties cheat sheet is here to make this easier for you.

The CSS position property sets how an element is positioned inside a document.

The elements are then positioned using the top, right, bottom, and left properties.

Note: These properties determine the final location of positioned elements and won't work unless the position property is defined. They may behave differently depending upon the position value.

Syntax

position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;

/* Global values */
position: inherit;
position: initial;
position: revert;
position: revert-layer;
position: unset;

Here is the meaning of its values in brief:

  • static: the default value for position property. It is a normal flow of the document.
  • relative: it's similar to static, but now we get the freedom to offset the position relative to itself.
  • absolute: it takes the elements out of the regular flow of the document.
  • fixed: it behaves the same as absolute, but now no space is created for the element in the document layout.
  • sticky: here element is positioned according to the document's normal flow, but it offsets relative to its nearest scrolling ancestor.

Of course, we will discuss these values individually in detail in the following few points, along with the global values.

Let's say we have four boxes with different background colors in our HTML code, and we have given them their respective ids:

<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>

Now, we can make use of the CSS position property to add some different values as needed:

* {
  box-sizing: border-box;
}

.box {
  display: inline-block;
  width: 200px;
  height: 50px;
  background: red;
  color: white;
}

#three {
  position: relative;
  top: 50px;
  left: 60px;
  background: blue;
}

As you can see, we have added an inline-block display to add the boxes with fixed width and height values and given it the red color. But for the div of id value #three, we are making it position: relative to itself with a custom offset top and left values. That's why when you see the output of the code above, you will see that the third box is out of the flow with respect to the positioning of the other three boxes.

Here's what it looks like:

CSS Positioning Cheat sheet

Let's also talk about the accessibility and performance concerns which are very important in production-level code. Here are a few points to consider:

  1. The first thing to understand here is that we should ensure that the elements positioned with an absolute or fixed value do not obscure other content when the page is zoomed in to increase the text size.
  2. If we have scrolling elements containing fixed or sticky content, then it can cause performance and accessibility issues. For example, as a user scrolls, the browser must repaint the sticky or fixed content in a new location.

Depending on your device hardware, the browser may not be able to manage the repaints of elements at 60 fps, causing accessibility concerns for people with sensitivities. To solve this, we can add will-change: transform to the positioned elements.

Okay, we now have enough starting knowledge about the position value, let's learn about each of its values independently in this cheat sheet.


Basic Level - CSS Position Properties Cheat Sheet

1. Static positioning 

Static is the default positioning for elements, and the elements remain 'static’ to the regular page flow.

So if a left/right/top/bottom and z-index properties are set, then these will have no effect. If we do not need an element to be rendered in a special way, then we can use this property. Here, the element is not a positioned box and is laid out according to its parent formatting context rules.

When both the inset properties in a given axis are set to auto, then they are resolved into a static position by aligning the box into its static-position rectangle. Hence, this property represents an approximation of the position the box would have had if it were position: static.

Example:

div {
   position: static;
   background-color: orange;
   text-align: center;
}

2. Relative positioning 

Relative positioned element is an element whose computed position value is according to the document's normal flow. Then it offsets relative to itself based on the values of top, right, bottom, and left.

The offset does not affect the position of any other elements. Hence, the space given for the element in the page layout is the same as if the position were static.

This value also creates a new stacking context when the value of z-index is not set to auto. If we have table-*-group, table-cell, and table-caption elements, then its effect on these elements remains undefined.

The top and bottom properties specify the vertical offset from its normal position, while the left and right properties specify the horizontal offset. The offset is purely a visual effect and doesn't affect the size or position of any other box, except if there is a scrollable overflow area of its ancestors.

Example:

div {
  position: relative;
  left: 20px;
  border: 3px solid blue;
}

3. Absolute positioning

Absolute positioned element is removed from the normal document flow, and no space is created for the element in the page layout.

It is positioned relative to its closest positioned ancestor, if there is any. Else, it is placed relative to the initial containing block. The final position of an element absolutely positioned is determined by the top, right, bottom, and left values.

We should also note that this value created a new stacking context when the value of z-index is not set to auto. The margins of absolutely positioned boxes do not collapse with other margins. If the element has margins, they are added to the offset, and the element establishes a new block formatting context for its contents.

Example:

div.one {
  position: relative;
  width: 500px;
  height: 150px;
  border: 2px solid blue;
}

div.two {
  position: absolute;
  top: 70px;
  right: 0;
  width: 300px;
  height: 50px;
  border: 2px solid yellow;
}

Note: Most of the time, absolutely positioned elements with height and width properties set up to auto are sized to fit their contents. However, non-replaced and absolutely positioned elements can fill the available vertical space when specified with both top and bottom properties leaving height. Also:

  • If both top and bottom are specified, then top will take precedence.
  • If both left and right are specified, left takes precedence when the document direction is ltr (for English, horizontal Japanese languages, etc.), and right takes precedence when direction is rtl (for Persian, Arabic, Hebrew languages, etc.).

Intermediate Level - CSS Position Properties Cheat Sheet

1. Fixed positioning

Fixed positioned element is removed from the normal document flow, and no space is created for the element in the page layout.

This element is positioned relative to the initial containing block established by the viewport. There is one exception, though, when one of its ancestors has a transform perspective or filter property set to something other than none. Also, if there is the will-change property set to transform, we see the same behavior in which the ancestor behaves as the containing block.

Its final position is determined by the values of top, right, bottom, and left offset properties. The value always creates a new stacking context.

Example:

div {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 200px;
  border: 3px solid blue;
}

This property is used to create a floating element that stays in the same position regardless of the scrolling. The box's position is fixed with respect to its reference rectangle. When attached to the viewport, it does not move when the document is scrolled. This property is also considered as the subset of absolute positioning.

Let's take another example. For instance, we want a box to remain at the top of each printed page. Then, we can use fixed positioning along with the default static one with the @media rules as:

@media screen {
  h1#first { position: fixed }
}

@media print {
  h1#first { position: static }
}

Note: If no ancestor established one, the fixed positioning containing the block is:

  • In continuous media: this is about the viewport. The fixed boxes do not move when the document is scrolled. In this respect, they are similar to another CSS property; background-attachment: fixed.
  • In paged media: this is about the page area of each page. The fixed boxes are thus replicated on every page, and they are fixed with respect to the page box only and are not affected by being seen through a viewport. Therefore, as a result, parts of fixed-positioned boxes that extend outside the initial containing block or page area cannot be scrolled and will not print.

For these fixed positioned elements, using large or negative values can quickly move elements outside the viewport and make the contents unreachable through scrolling or other means.

One privacy and security consideration we may need to consider is that position: fixed can allow a page to emulate modal dialogs. This could trick a user into thinking they are interacting with the user agent and entering sensitive information that their page can capture. For this, we must ensure that their native dialogs are positioned in ways that the page cannot emulate.

2. Sticky positioning

Sticky element is positioned according to the document's normal flow and then offset relative to its nearest scrolling ancestor and containing block.

This containing block can also be the nearest block-level ancestor, including table-related elements based on the values of top, right, bottom, and left. These offset values do not affect the position of any other elements, and this value always creates a new stacking context.

Note: A sticky element 'sticks' to its nearest ancestor with a 'scroll mechanism' even if that ancestor is not the nearest scrolling ancestor. This is created when the overflow property is set to hidden, scroll, auto, or overlay.

Example:

div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  padding: 10px;
  background-color: orange;
  border: 1px solid blue;
}

The element with position: sticky is treated as relatively positioned until its containing block crosses a specified threshold within the container it scrolls. This can be setting a top to a value other than auto.

This property is identical to relative, except that its offsets are automatically adjusted in reference to the nearest ancestor in whichever axes the inset properties are not both auto so that the box is in view.

For stickily positioned boxes, the inset is relative to the relevant scrollport's size, and negative values are allowed. An auto value represents a zero inset.

Note: If we use multiple stickily positioned boxes in the same container, then the offsets are independent and might overlap.

Let's take another example where the nearest scrollport is '300px' tall, the sticky box's border box is '200px' tall and has top: 20px applied to it. Then the top-edge of the nearest scrollport is '20px', and the bottom-edge inset is '0px' which results in a sticky view rectangle that is '280px' tall.

3. Global values of position: Inherit positioning 

From here, we will be learning about the global values of positioning. 'Global' means that these values can appear in other CSS properties like color, background, etc., and is not local to the position property.

In CSS, inheritance controls what happens when no value is specified for a property or an element. By default, these are set to the computed value of the parent element. Only the document's root element gets the initial value given in the property's summary.

In terms of positioning, the inherit position allows us to specify the inheritance explicitly and causes the element to take the computed value of the position property from its parent element.

Example:

#div1 {
  position: relative;
  color: red;
}

#div1Child {
  position: inherit;
}

Here, div1 has the position set to relative. The child element inherits the color, but the position property is not inheritable. On the other hand, in div1Child, the position property is set to inherit, and this will make it inherit the value of its position by its parent element. Hence, the position of div1Child will be relative.

4. Initial positioning 

The initial keyword applies the initial or the default value of the position property to the element.

Its usage depends on whether the position property is inherited or not:

  • If it is inherited, then the initial value is only used on the root element.
  • If it is not inherited, the initial value is used on all elements. Here, the value may be unexpected, so we should consider using other values like inherit, unset, revert, or revert-layer.

Example:

.div {
  position: initial;
  padding: 50px;
  background-color: orange
}

Here, the div has the initial position, which makes the element take the initial value of the position property, and that is position: static.

5. Revert positioning

The revert keyword reverts the cascade value of the position property from its current value to the value the property would have had if no changes had been made to the current element.

This resets the property to its inherited value if it inherits from its parent or to the default value established by the user agent's stylesheet.

Note: This keyword removes all the styles from the cascade that have been overridden. It doesn't affect rules applied to the children of an element you reset.

Example:

div {
  position: absolute;
  background-color: orange
}

.div {
  position: revert;
  margin-top: 8px;
  padding: 50px
}

Here the div element is set to have an absolute position. Note that by default, this value is set to static. Now, as div.div's property is set to revert, therefore it resets the position properly from absolute to static.

6. Revert layer positioning

The revert-layer keyword rolls back the value of a position property in a cascade layer to the property's value in a CSS rule matching the element in a previous cascade layer.

The property's value will be recalculated as if no rules were specified on the target element in the current cascade layer.

Note: This is an experimental global value. You need to check the browser compatibility for it to use in production code.

If there is no cascade layer to revert, the property value rolls back to the computed value derived from the current layer. Also, if there is no matching CSS rule, the property value will roll back to the style defined in the previous style origin.

One crucial difference to note between revert-layer and revert is that the latter lets us remove styles applied in the origin. If the revert-layer is set on a property outside a layer, then the value will roll back to the default established by the user agent's stylesheet.

Example:

@layer default {
  a { color: maroon; }
}

@layer theme {
  a { color: var(--brand-primary, purple); }
  
  .no-theme { color: revert-layer; }
}

In the example above, we are using the color property to show how the revert-layer works on the @layer rule. The link tag with the no-theme class will roll back to use the value set in the default layer. When revert-layer is used in un-layered styles above it, it behaves the same as revert.

7. Unset positioning

The unset keyword resets a position property to its inherited value if the property naturally inherits from its parent and to its initial value if not.

It behaves differently on inherited and non-inherited properties. When the unset value is set on inherited property, it resets the property value to its inherited value. On the other hand, it resets a non-inherited property to its initial value.

Hence, the unset behaves like the inherit keyword for inherited property and like initial for the non-inherited property.

Example:

.div {
  margin-top: 8px;
  padding: 50px;
  position: unset;
}

Here we are setting the position value to be unset, which in itself is an inherited property. So, it will behave like a inherit keyword here, causing it to have a static positioning.

Advanced Level - CSS Position Properties Cheat Sheet

1. Static positioning demo 

Here's a demo example showing static positioning in detail:


<html>
  <head>
    <style>
      p {
        margin: 0;
      }
      
div:first-child {
        position: static;
        background-color: orange;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div>Static Position</div>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.</p>
  </body>
</html>

When you run this in your browser, you should see the following output:

CSS positioning

2. Relative positioning demo

In this example, we are using the relative positioning for the div:


<html>
  <head>
    <style>
      div {
        position: relative;
        left: 50px;
        border: 5px solid orange;
      }
    </style>
  </head>
  <body>
    <h1>Realtive Position</h1>
    <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.</div>
  </body>
</html>

Here's what you should see in the browser:

CSS positioning cheat sheet

3. Absolute positioning demo

Here, we will be using absolute positioning for the div having the two class. As a result, it is positioned with the offset values provided to it.


<html>
  <head>
    <style>
      div.one {
        position: relative;
        width: 500px;
        height: 150px;
        border: 3px solid orange;
      }
      
div.two {
        position: absolute;
        top: 50px;
        right: 50px;
        width: 400px;
        height: 150px;
        border: 3px dashed green;
      }
    </style>
  </head>
  <body>
    <h2>Absolute Position</h2>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.
    <div class="one">Relative position
      <div class="two">Absolute position</div>
    </div>
  </body>
</html>

This results in the following output:

CSS positioning cheat sheet

4. Fixed positioning demo

Here, we will fix the position of a div to the top-right corner, and we see while scrolling the content, its position remains fixed.


<html>
  <head>
    <style>
      div {
        position: fixed;
        top: 0;
        right: 0;
        width: 150px;
        background-color: orange;
      }
    </style>
  </head>
  <body>
    <h2>Fixed Position</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.</p>
    //...
    <div>
      Fixed positioned div
    </div>
  </body>
</html>

Here's the output:

CSS positioning cheat sheet

5. Sticky positioning demo

In the demo below, we are trying to make a div have a sticky position so that even if we scroll past the content, we can still see the sticky element:


<html>
  <head>
    <style>
      div.sticky {
        position: sticky;
        top: 0;
        padding: 15px;
        background-color: orange;
      }
    </style>
  </head>
  <body>
    <h2>Sticky Position</h2>
    <div class="sticky">Sticky!</div>
    <div style="padding-bottom:1000px">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas faucibus justo sapien, nec scelerisque lacus volutpat in.</p>
      //...
    </div>
  </body>
</html>

This will result in the following:

CSS positioning cheat sheet

Conclusion - CSS Position Properties Cheat Sheet

This CSS position properties cheat sheet covered why positioning is needed with a basic example. Then we went through all the possible properties involved in positioning an element in a document with more detailed and practical demos towards the end.
We hope this cheat sheet will help you better position elements on a webpage in your next project.

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

Copyright @2023 Flexiple Inc