CodeBlanks Logo Icon CodeBlanks

Position absolute

CSS course · Beginner · Lesson 69/82

Position elements with position: absolute.

Free placement with position: absolute

position: absolute pulls an element out of the normal document flow. Surrounding elements fill its place, behaving as if it were not there. The element is then placed relative to its nearest positioned ancestor.

This value is ideal for putting a badge in a card's corner or pinning an icon next to text. Placement is done with top, right, bottom, left.

Containing block

A position: absolute element is placed relative to its nearest ancestor whose position value is not static. That ancestor is called the containing block. If no such ancestor exists, the element is placed relative to the browser window.

Practical tip: give the wrapper position: relative and the child position: absolute. This combo is the most common pattern.

Corners with zero and percent

On a position: absolute element, top: 0 and right: 0 stick it to the top-right corner of its container. top: 50% and left: 50% measure from the container's top-left corner to center the element.

Percent values are computed against the containing block's size. This is very handy for placing badges, icons and tooltips.

Exercise Place the badge top-right

Write a .card .badge descendant selector and assign three declarations: position: absolute, top: 0, right: 0. The badge will then stick to the card's top-right corner. (Assume the card has position: relative.)

Show example solution
/* place the badge top-right */
.card .badge {
  position: absolute;
  top: 0;
  right: 0;
}

Test yourself

  1. Which is the badge's containing block here?

    .card {
      position: relative;
    }
    .card .badge {
      position: absolute;
      top: 0;
      right: 0;
    }
    • The .card class
    • The browser window
    • The html root tag
    • The badge itself
    Show answer

    The .card class — Correct. .card is the badge's nearest positioned ancestor; it is the containing block.

  2. Free-place the tooltip

    .tooltip {
      ____;
      top: 100%;
      left: 0;
    }
    Show answer
    .tooltip {
      position: absolute;
      top: 100%;
      left: 0;
    }
  3. Match each value to its meaning

    absolute
    Leaves the flow
    relative
    Becomes container
    static
    Default flow

All lessons in Beginner