Premium Features

Download Video

Position Relative, Z-Index, and Object-Fit

Published 3 years ago

Position relative is a CSS property that allows you to reposition whatever element it is applied to, while keeping that element in the document flow.

You can move an element with position: relative using the CSS properties top, right, bottom, and left, however, these properties only work when applied to an element of relative and absolute. The difference between relative and absolute is, relative will keep the element its applied to in the document flow, while absolute will take the element out of it. Which you use typically comes down to making decisions on how you want your site to scale when used on a mobile device, or how you want your elements overlapped on top of each other.


To overlap elements on top of each other, you can alter elements' z-axis positioning using the CSS property z-index. Elements by default will be placed next to, or on top of eachother, within the document flow. When position relative or absolute is applied though, the elements can be moved on top of eachother using a sub-position property like top. When two elements are overlaid on top of each other, one may be covering the other (such as a background image covering text that's supposed to go on top of it). To move the background image to the back, and the text to the front, you'll want to set the text element's z-index property to something greater than 1, such as 10. This will ensure the text is brought forward on the screen, and that it is no longer hidden by the background image. But note, z-index will only ever work if it is applied to an element that has a position of relative or absolute.


Object fit is a CSS property that determines how an element fits inside of its parent container. The element's parent container must have its width and height set, otherwise, the property may not take effect when applied.

The most common value object-fit is set to is cover, this will ensure that the element "covers" the full width and height of its parent container. It's a great way to fill up any pesky white space that may show due to the inherent aspect ratio of your image, especially because object-fit maintains your image's aspect ratio no matter its size or the scale of the screen.

In all, if you want an element to take up the full width and height of its parent container while maintaining its aspect ratio, then that's a sure-fire indicator you'll want to use the object-fit property.


Want to participate?

Create a free Chris Courses account to begin


No comments yet, be the first to add one

Providing the lift to launch your development career

© 2024 Chris Courses. All rights reserved.