Facing the CSS: Position
This past week, I asked myself a question: “Do I know CSS?” I’ve learned the language. I know how to read it. It made sense to me. But I’ve never actually styled anything from scratch. So could I say that I truly knew CSS? I had to play it on the safe side, so I challenged myself to style my existing projects from scratch!
From this experience, I immediately learned that CSS is not intuitive. I’ve gone through and refreshed myself on several different CSS properties, and today I’d like to share what I learned about position
.
There are five different values for position
: static
, relative
, fixed
, absolute
, and sticky
. I’ll go over each of them below.
static
The static
property is the document default when a value isn’t specified, and positions HTML elements according to the flow of your page.
div.static { position: static;}
relative
The relative
property is similar to static
, but with four added properties — top
, right
, bottom
, and left
. The added properties allow you to shift the element from its position, which is relevant to its parent, while keeping the parent and sibling elements in tact.
div.relative { position: relative; left: 100px; top: 50px;}
fixed
The fixed
property will keep the element in its viewport position, regardless of page scrolls. This property can also be used with top
, right
, bottom
, and left
.
div.fixed { position: fixed; left: 0px; top: 0px;}
absolute
The absolute
property completely removes an element from its flow, ignoring all other elements, save for any ancestor elements. If there are ancestor elements, the absolute
element will be positioned relative to the nearest ancestor element that has any position other than static
. Otherwise, it is positioned using the document body. This property can also be used with top
, right
, bottom
, and left
.
div.absolute { position: absolute; left: 0px; top: 0px;}
sticky
The sticky
position is a combination of the fixed
and relative
positions. By default, the sticky
element is relative
. It’s not until you scroll out of its viewport, that the element becomes fixed
and moves with the page. When setting a position to sticky
, you must specify at least one top
, right
, bottom
, or left
property value.
div.sticky { position: sticky; top: 50px;}
Still stuck? Check out the video below by Web Dev Simplified!
If you’d like your elements to overlap, but can’t figure out how to bring one element forward, adjust its z-index
!