How to learn CSS Positions with examples
Learn how to move and position for HTML elements
If you are a front-end developer, knowing to position elements with css is critical knowledge. CSS has five 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>
##static
Static works on document flow by default for elements. Every element is related to the document flow.
relative
The element can be moved relative to his current position, using use top, left, and bottom.,
Example: Move the current card 50px from the left. It takes the present position as a reference. %[jsfiddle.net/danywalls4/xdmynj0a/33/]
absolute
The element jumps from the normal flow, but without breaking other elements' positions, you can move everywhere because it references 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 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 the top, don't care use scroll the main with position fixed it will stay.
sticky
The element with position sticky keeps the place relative to the user scroll position.
Example: The card with position sticky inside the main will keep his position his container is visible.
Final
This is a quick overview of the position in CSS. I hope an example helps you understand a slight CSS position.