Overlapping Elements with CSS Grid

1 March 2019 - 8:38am

One of the challenges that a web developer sometimes faces is to make two elements overlap. This is easy enough to achieve using position: absolute, but one often runs into the problem: What if you're not sure which element will be taller?

Say you have the following CSS:

.image-wrapper
{
    background: black;
    position: relative;
}

.image-wrapper img
{
    height: auto;
    width: 100%;
}

.image-wrapper .caption
{
    background: rgba(255, 255, 255, 0.9);
    font-size: 24px;
    left: 20px;
    line-height: 1.5;
    padding: 40px;
    position: absolute;
    right: 20px;
    top: 20px;
}

Which will look like this example:

Example of absolute positioning, the caption overflows the image and overlaps the following content

If the caption is long enough, it will break out of the image and start covering anything below it, obscuring text and ruining everything.

So how do we deal with this? The newest addition to a developer's toolbox, CSS grid. Grid allows you to overlap elements, and will automatically size a cell to the height of the largest element:

.image-wrapper
{
    align-items: start;
    background: black;
    /* We can even support Internet Explorer 10 and 11, using the older spec */
    display: -ms-grid;
    display: grid;
    /* Required for -ms-grid to handle placement correctly */
    -ms-grid-columns: 100%;
    -ms-grid-row-align: start;
}

.image-wrapper img
{
    /* No need to specify -ms-grid-row or -ms-grid-column, since -ms-grid doesn't
    support auto-layout, so will automatically place everything into the first
    row and column */
    grid-column: 1;
    grid-row: 1;
    height: auto;
    width: 100%;
}

.image-wrapper .caption
{
    background: rgba(255, 255, 255, 0.9);
    font-size: 24px;
    grid-column: 1;
    grid-row: 1;
    line-height: 1.5;
    margin: 20px;
    padding: 40px;
}

This will instead result in:

Example of grid positioning, the caption increases the size of the container and the image does not overlap the following content

The image-wrapper contains both the image and the caption, no matter which is higher, the image-wrapper will always have the correct height.