What exactly does the CSS position property do?

Photo by Halacious on Unsplash
  • Relative
  • Absolute
  • Fixed
  • Sticky

Position: Static

By default, a web page and its elements are displayed in static position. The elements appear in the viewport according to the document flow and the writing method of the browser. Some browsers display left-to-right, right-to-left, or vertically down the page depending on your country and language. A page without CSS to explicitly change the ordering or positioning of elements is said to be in Normal Flow.

Position: Relative

Whenever an object is moved from its static position in a layout, it’s moved based on a reference. In an element with position: relative applied, it is positioned relative to where it would be in Normal Flow.

Position: Absolute

Setting position: absolute on an element removes it and the space it would normally take from the document flow entirely. The element is then positioned relative to its containing block - which is either a positioned ancestor (a parent element whose position is anything but static), or the browser viewport itself, if such a parent doesn’t exist.

Parent in default `static` position & Child in `absolute` position
<body>
<div class="parent">
<p>Parent</p>
<div class="child">
<p>Child</p>
</div>
</div>
</body>
.parent {
height: 150px;
width: 150px;
background-color: orangered;
border: 1px solid red;
text-align: center;
}
.child {
position: absolute;
top: 50px;
left: 50%;
background-color: white;
border: 1px solid purple;
margin: 10px;
}
Parent in `relative` position & Child in `absolute` position
.parent {
position: relative;
height: 150px;
width: 150px;
background-color: orangered;
border: 1px solid red;
text-align: center;
}
.child {
position: absolute;
top: 50px;
left: 50%;
background-color: white;
border: 1px solid purple;
margin: 10px;
}

Position: Fixed

If an element should be positioned according to the viewport, we can use fixed positioning. Like with absolute positioning, an element with position: fixed applied will be completely removed from the document flow.

Position: Sticky

The final position value we have to talk about is sticky. A sticky element works a bit differently than what we’ve seen so far. Its actual position value toggles between relative and fixed, depending on the user’s scroll position.

A Word on Normal Flow

Good document structure is key part of web design, especially accessibility-first minded design. A well structured html document is crucial for the users that rely on screen readers and will never see the CSS, and is just as important for those that do.

I’m Ash, a developer with a passion for web design, accessibility, and learning!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store