Using the CSS Grid Layout Module in web design becomes more and more feasible as more browsers begin to support it. While creating layouts filling in grid cells, there might come a moment, though, when you want to achieve more complicated things.
It was once tables, then margins and floats, then flexbox and now grid: CSS always steered towards new…Read more
For instance, you might want to slightly move around some of the grid items stuck in their grid areas. You also might want to move them out of the grid container (overflow), or over each other (overlap), or just… to some empty space around.
So, in this post, I’ll show you how you can move, order, overflow, overlap, and size grid items when you use the CSS Grid Layout Module.
Create a CSS grid
First, let’s create a simple CSS grid with one row and three columns.
In the HTML, we create a bunch of divs where the grid container contains the three grid items.
Grid items are rendered on the screen in the order they appear in the HTML source code.
In the previous section, when the center item was moved left, it was placed on top of the left item by the browser. This happened because in the HTML, <div class='grid-center'> comes after <div class='grid-left'>, hence the center item is rendered after (and over) the left one.
However, we can change the order grid items using the z-index or the order CSS properties.
Using the z-index: 1; rule, the left grid item got a higher stacking context.
As in the CSS Grid Layout module, changing the element order in HTML doesn’t affect the grid layout, you can also put <div class='grid-center'> before <div class='grid-left'> in the HTML. Only do this, though, if the updated HTML code doesn’t harm accessibility.
Size grid items
If you use auto-sized rows or columns for a grid item (using auto, fr, gr units), it will shrink to make space for its neighbouring item that has grown in size only if said item was not sized by transform or a negative margin.
Remember, in our sample grid, all three columns take one fraction (fr) of the grid container. Take a look at how all three items look like after the left one is resized in two different ways.
1. Sized with width and height
Here, we change the size of the left item using the width and height properties. As a result, it stays inside the grid container.