inset
Definition
The inset property is a shorthand property that specifies the position of an element in relation to its containing element. It allows you to specify the top, right, bottom, and left offsets of an element all at once. The offsets can be specified in any order and can be expressed as a length value, a percentage value, or the keywords auto or initial.
Examples
This code centers an absolutely positioned element both vertically and horizontally within its containing element. The inset property sets the top, right, bottom, and left offsets of the element to 0, which aligns it with the edges of the containing element. The margin property then centers the element within the containing element:
.absolute {
position: absolute;
inset: 0;
margin: auto;
width: 50%;
height: 50%;
}
This code moves a relatively positioned element 20 pixels down and 20 pixels to the right from the top-left corner of its containing element. The inset property sets the top and left offsets to 20px and the right and bottom offsets to 0:
.relative {
position: relative;
inset: 20px 0 0 20px;
}
This code makes an element fill the entire viewport by setting its position to fixed and using inset: 0 to position it at the edges of the viewport. The width and height properties are set to 100% to make the element fill the entire viewport:
.fill {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
Values
Value | Description |
---|---|
length | Specifies a fixed offset from the containing element's edge. |
percentage | Specifies an offset as a percentage of the containing element's size. |
auto | The default value. The element's position is determined by its layout rules. |
initial | Sets the property to its default value. |
Best Practices
- Use position: absolute or position: fixed to position an element with the inset property.
- Always specify at least one offset value for the inset property.
- Use percentage values for the offsets if you want the element to be positioned relative to the containing element's size.
- Avoid using negative offset values with the inset property, as this can cause unexpected layout behavior.
- If you need to set different offsets for the top/bottom or right/left edges, use the longhand properties top, right, bottom, and left instead of inset.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | No | Yes | Yes |