Absolute Positioning with Grid
Examples of how absolute positioning can affect the normal flow within a grid.
You can use absolute positioning within a grid, just as you can within a regular block. If you set position: relative
on a grid item, then use position: absolute
on one of its children, any positioning you specify will apply within that grid item.
Here's an example of using absolute positioning to place an icon at the bottom right corner of a grid item:
However, there are some things to keep in mind when positioning items within a grid.
Positioned Items don't Participate in the Grid Layout
Absolutely positioned items don't participate in the grid layout, and they don't take up space. Therefore, they don't affect the placement of other grid items.
Here are two examples to demonstrate.
Without Absolute Positioning
In this example I've explicitly set box 4 to go into the 2nd column on the first row, and all other boxes are set to auto
. Box 4 effectively pushes box 2 out of its slot — boxes 2 and 3 are auto-placed into the next available grid areas. Therefore, box 4 affected the placement of the grid items.
With Absolute Positioning
By setting box 4 to position: absolute
, it's still located in box 2's position, but box 2 remains in that position unaffected. Box 3 is also unaffected.
Positioned Items Shrink to Fit their Contents
Another thing to remember is that, positioned items shrink to fit their contents (you can see this effect in the previous example).
This is different to what normal grid items do. Normal grid items stretch to fit their grid area, so if you specify that a grid item spans two columns and two rows, it will do just that.
The auto
Value in Positioned Items
On normal grid items, the auto
value for a grid-placement property resolves to span 1
, but on absolutely positioned items, it resolves to the padding edge of the grid container. This could result in some seemingly weird stuff happening if you're not aware of how it works.
The auto
value is the initial value for the grid-placement properties, so this will happen by default if you don't specify a different value.