GenRater

Blogs by Rahul J Krishnan

Usage of CSS inset Property

#webdev

The CSS inset property is a shorthand for top, right, bottom, and left properties. It does not affect statically positioned items. For the inset property to take effect the item must have its position set to absolute, fixed, or relative.

inset Property Syntax

The syntax of inset property is similar to that of the syntax of margin or padding properties. It can take a maximum of four values specifying values in the clockwise direction starting with the top and a minimum of one value which specifies the same value to be applied to all directions.

The inset property can take values in length(px, em), as a percentage, or global values(inherit, initial, revert, or unset). The default value for inset is auto.

/* <length> values */
inset: 10px; /* value applied to all edges */
inset: 4px 8px; /* top/bottom left/right */
inset: 5px 15px 10px; /* top left/right bottom */
inset: 2.4em 3em 3em 3em; /* top right bottom left */

/* <percentage>s of the width (left/right) or height (top/bottom) of the containing block */
inset: 10% 5% 5% 5%;

/* Keyword value */
inset: auto;

/* Global values */
inset: inherit;
inset: initial;
inset: revert;
inset: unset;

Comparison with inset Property

Let's position an element with top, right, bottom, and left properties.

.element {
  position: absolute;
  top: 1em;
  right: 1em;
  bottom: 1em;
  left: 1em;
}

We can replace this four-line code with a single-line inset property.

.element {
  position: absolute;
  inset: 1em;
}

Now let's say we want to position an item on the bottom right of our screen in the traditional way we can achieve it with the code below:

.element {
  position: fixed;
  right: 2rem;
  bottom: 2rem;
}

To replicate this same effect with the inset property we will have to ignore one or more of the four values we specify in the inset property so for that we should be using auto as the value. The code will be as below:

.element {
  position: fixed;
  inset: auto 2rem 2rem auto;
}

So when we are setting a value as auto it is the same as we are not setting a value for that direction. Here we have set auto for the top and bottom values in the inset property. Thus we can achieve the same result as the traditional code.

Rahul

Rahul

I'm a front end developer hailing from Kochi, Kerala, India.

Leave a comment

Thanks for reading.