Absolute

Absolute positioning takes an element out of the page's flow and places it relative to its nearest positioned ancestor, usually a parent with position relative.

Apprentice · CSS · Updated

By

After this lesson you can

  • Place an element at a spot inside its parent with absolute positioning and a relatively positioned parent

Key takeaways

  • Absolute positioning takes an element out of the page's flow, so the elements after it move up into its space.
  • It's placed relative to its nearest ancestor whose position isn't static, usually a parent you've made relative.
  • With no positioned ancestor, it's placed relative to the page, and it scrolls with the page.

absolute position takes the element out of the page's flow (the space it would have used is no longer kept) and places it relative to its nearest ancestor that has a position other than static, usually a parent you've given position: relative. If there's no such ancestor, it's placed relative to the page.

.div-2 {
    position: absolute;
    left: 30px;
    top: 30px;
}

Div 2 placed 30px from the page's top left corner, over div 1, and div 3 moved up into the space div 2 left

As the page is scrolled, all elements scroll together.

After scrolling, div 2 has moved up with the page, still sitting over div 1

Inside a relative parent

Give the parent position: relative and it becomes the frame the absolute element is measured from.

.product-card {
    position: relative;
}

.sale-badge {
    position: absolute;
    top: 0;
    left: 0;
}

The sale badge now sits in the product card's top left corner, and it moves wherever the card goes.

Do it: pin the Sale badge to the book card's corner

A bookstore page shows Little Women on a card, with a red Sale badge. Right now the badge sits on its own line above the title. It should sit in the card's top right corner, over the card, and move wherever the card goes.

Here is where each part should end up:

Part Where it should be
The book card, class book-card where it is now; it's the frame the badge is measured from
The Sale badge, class sale-badge out of the card's flow, 8px below the card's top edge and 8px in from its right edge
The title, Little Women moves up into the space the badge left

Your job: write CSS for the card and the badge.

  • Make the book card the frame its badge is measured from.
  • Take the badge out of the flow and place it inside the card.
  • Put the badge 8px from the card's top and 8px from the card's right.

Practiced live on the lesson page: write the CSS right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Sale badges on product cards, close buttons in a corner and labels over a picture are all absolute elements inside a relative parent.

Key terms

Cheat sheets