Stacking items on top of one another used to be a little bit of a pain. Usually, this would involve using CSS a little bit like this:
.stacked-parent { position: relative; } .stacked-item { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
Pretty horrible. Too many lines of code involved (and this omits cross browser code). This is the most simple of use cases, where both stacked items would be aligned to the centre of the parent container.
The issues here is that by making the child elements absolutely positioned, we have removed them from the document flow. This is going to cause us some headaches with layout and will mean likely we have to set a specific height to the parent container, or even worse, dynamic height with frontend JS. Yuk.
So, what can we achieve with CSS Grid?
CSS Grid’s layout engine is wonderful. With just a couple of lines of code we can achieve the same stacked elements in the centre of the parent, whilst retaining document flow and native element heights. Hoorah.
.stack { display: grid; place-content: center; > * { grid-area: 1 / 1; } }
A lovely little snippet to save you time if and when you need to stack child elements on top of one another inside a parent container.