Let's learn about the different modes of CSS positioning.
CSS has a position property. Its values can be set to static
, relative
, absolute
, and fixed
.
What is CSS positioning?
CSS positioning is a way to “nudge” an HTML element, such as a div
, in any direction we want, be it top, right, bottom, or left. Note that this “nudging” doesn’t remove the element from the normal document flow, it displaces it.
Here’s an example of three divs.
Each div’s display property is set to inline-block so that they all appear next to one another, rather than on top of one another.
Notice how the middle div is slightly nudged away from the top edge. We’re setting its position
to relative
, using div.bg2
. The div.bg2
selector instructs the browser to find the HTML <div>
element that has a class attribute set to bg2
and
apply the position relative
to it.
Notice that the div CSS selector on line 10 of the CSS code sets all the divs to position: static
and top: 40px
.
The CSS position
property is, by default, set to static
and, therefore, we don’t have to specify it. When the position is static, we cannot “nudge” elements out of the flow with the top
property.
When the value of the position
property is set to relative
, the top
property suddenly starts working.
How does a browser decide if will use the position static
set in the div element CSS selector or if it will use the position: relative
set in the div.bg2
CSS selector?
It resolves this problem with something that’s called CSS specificity. CSS specificity works like this: a more specific CSS selector will take precedence over a more general CSS selector.
So, we have two CSS selectors competing for the position
properties in our example above. The first CSS selector, div
, sets the position
property to the value of static
. The second competing CSS selector, div.bg2
, sets the position
property to the value of relative
.
The second CSS selector wins because its instructions are more specific, that is, to target the div
that has the class of bg2
. On the other hand, the first selector has less specific instructions, that is, to target all the div
elements.