CSS Positioning
Publish date: Aug 2, 2019
Last updated: Apr 22, 2020
Last updated: Apr 22, 2020
The position property specifies the type of positioning method to be used by renderer (browser) for an element1.
There are five different position values:
- static
- relative
- fixed
- absolute
- sticky
static
static
is the default position style that all HTML elements will have when they are added onto page.- are not affected by the
top
,bottom
,left
, andright
properties.
relative
- Are positioned relative to their normal position
relative
allows to usetop
,bottom
,left
, andright
css properties relative to its normal position.
fixed
- is positioned relative to the viewport, which means it always stays in the same place
fixed
has nothing to do with parent. Moves with the page.- DOM removes the element from the page
- Then builds the rest of the page
- Then put this element on the top
- Hence it overlays other elements
absolute
- is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
absolute
completely remove element from document flow and treats it as if its not a part of document at allrelative
andabsolute
plays nicely
sticky
- A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it “sticks” in place (like position:fixed).
sticky
combination offixed
andrelative
position.- Needs a
position
to work
- Needs a
position: sticky;
top: 0.25rem;
z-index
The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).
z-index: -1; /* behind */
To centre divs horizontally use
#container {
width: 800px;
margin-left: auto;
margin-right: auto;
}
This doesn’t work vertically
@media (min-width: 600px) {
p {
font-size: 1.25rem;
}
}
#footer {
clear: both;
}
- Media query block
- breakpoint, could be
max-width
as well. - Clear all floating styles before we display
Mobile-first approach - think about how your site will look right from the start