Quick Guide to Positioning with CSS Inset

Positioning with the CSS inset property is a straightforward way to specify an element's position relative to its nearest positioned ancestor (not static).

inset is simply shorthand for top, left, right, and bottom to position your elements.

I think it'll make most sense when you see an example:

Example

Let's create a simple example of positioning a div element within its parent using inset.

HTML:

<div class="container">
  <div class="box">Centered Box</div>
</div>

CSS:

.container {
  position: relative; /* This makes it the reference for its absolutely positioned children */
  width: 100%;
  height: 300px;
  background-color: lightgrey;
}

.box {
  position: absolute;
  inset: 50px; /* This applies 50px from all sides: top, right, bottom, and left */
  background-color: skyblue;
  text-align: center;
  line-height: 200px; /* Center text vertically */
}

The result is a skyblue box centered inside a lightgrey container with a 50px gap from all sides of the container. This is a simple way to center elements or create padding effects using CSS positioning and the inset property.

Here's a little CodePen to experiment with different inset to see how the position of the .box changes relative to its parent container:

Not limited to one value

The inset property can accept one, two, three, or four values:

  • One value: Applies the same value to all four sides (top, right, bottom, left).
  • Two values: The first value applies to the top and bottom, the second to the left and right.
  • Three values: The first value applies to the top, the second to the left and right, and the third to the bottom.
  • Four values: Applies to the top, right, bottom, and left, respectively.
CSS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.