Problems with CSS grid and image

I have been playing around with CSS Grid. For the most part it is the most simple thing in the world, but I have been stuck with a problem for ages now.

I made a very simple test layout. I have two divs which are nested inside a wrapper.
One contains an image and a h3 tag, and the other just contains some random text.

<div class="wrapper">
		
		<div class="box1">
			<img src="img/img.jpg" alt="#">
			<h3>text</h3>
		</div>
		<div class="box2">
			<p>text</p>
        </div>			
</div>

The problem is getting the h3 text on top of the image. Normally you would do that by giving the h3 tag a position of absolute and the img tag a position of relative.

.wrapper {
	display: grid;
	grid-template-columns: 40% 60%;
}

.box1 img {
	position: relative;
	vertical-align: bottom;
	width: 100%;
    height: 100%;
	filter: brightness(50%);

}
.box1 h3 {
	position: absolute;
	color: white;	
}

I tried doing this, but it does not work. The text within the h3 tag vill still display underneath the image, expanding the column, and it will also spill over to the other column.

Plan B was to remove the img tag and instead use CSS background-image. This does the trick, but it also crops 90% of the image, because now it relies on the height of the content in the neighbouring column. So if box2 only has a line of text that takes up 5px, then the image height in box1 will only be 5px as well, despite having set it to 100%.
This problem can be overcome by giving the image a specific height in px, but then I ruin the responsive behaviour i had when using %.

I feel like this is a very simple problem with a very simple solution, but I can’t figure out how to fix it.

Have you tried setting positioning styles (eg, top, left) for the h3? Setting top: 0 seems to work.

You may also want to set .box1 to be position:relative, so the h3's position is based on that box, not the whole page.

1 Like

I found a solution to this, and it involves using more grid!!

We can make you class of box1 a grid as well:

.box1 {
    display: grid;
}

Now we can add the header and image to the same grid-row and grid-column to overlap them:

.box1 img {
    grid-row: 1 / 2;
    grid-column: 1 / 2;
}

.box1 h3 {
    grid-row: 1 / 2;
    grid-column: 1 / 2;
}

The problem now is our header image goes behind the image, so we just need a quick fix:

.box1 h3 {
    grid-row: 1 / 2;
    grid-column: 1 / 2;

    z-index: 1;
    margin: auto; // Optional, centers the h3 element 
                          // horizontally and vertically
}

Hope this helps :slight_smile: