DEV Community

Cover image for Head start CSS Positions with examples
Dany Paredes
Dany Paredes

Posted on

Head start CSS Positions with examples

If you are frontend developer, know to position elements with css is critical knowledge. CSS have 5 position types, I will try to write a small example with each of them.

Every CSS Position example use the following HTML structure

<main>
    <div class="card card-1">
        card 1
    </div>
    <div class="card card-2">
        card-2
    </div>
    <div class="card card-3">
        card-3
    </div>
</main>
Enter fullscreen mode Exit fullscreen mode

static

Static is based to document flow and is by default for elements, every element will be position based in the document flow.

relative

The element can be moved relative to his current position, using use top, left right and bottom.

Example: Move the current card 50px from left, it takes his current position as reference.

absolute

The element jump from the normal flow but without break other elements positions, you can move everywhere because it as reference the body as default.

Example, the main have a size like 250px and .card-3 with absolute position is top 0 it will get out from parent.

If want to move close to parent, set the position the use relative or absolute to parent.

The .card-3 keep the position related to the parent, but the .card-3 is over .card-1 how to move card-1 to top ?

The z-index help us to move element over elements, just set a higher value and move it to the top.

fixed

The element with position fixed it jump from normal flow but is relative to the viewport,

Example: You want to have a message on top or modal don't care if the use scroll page is a use case.

First increment body height to 150vh and set position fixed to main and top:100px from top, don't care use scroll the main with position fixed it will stay.

sticky

The element with position sticky keep the position relative to the user scroll position.

Example: The card with position sticky inside the main will keep his position his container is visible.

That's it!

This is a quick overview of position in CSS, I hope example to help you to understand a little CSS positions.

Top comments (0)