I’m trying to create a two-column layout with an image on the left and text content on the right using CSS grid. Yet the image keeps overflowing.
I’ve been trying to fix it but I’ve only been able by using absolute values which… doesn’t seem right.
I’m just learning about web dev and honestly I just wish to understand why this happend and How can I prevent such a thing from happenning when using css grid
* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: 2px solid red;
}
html {
font-family: sans-serif;
}
header {
display: flex;
height: 3.5rem;
justify-content: space-between;
margin: 0 2rem;
}
header>* {
display: flex;
align-items: center;
gap: 1rem;
}
span {
height: 2rem;
display: flex;
align-items: center;
}
a {
text-decoration: none;
}
.hero {
display: grid;
grid-template-columns: 1fr 1fr;
height: 70vh;
}
img {
object-fit: cover;
width: 100%;
max-height: 100%
}
<div class="hero">
<article>
<h1>Access a library of free design resources</h1>
<p>The best resources and books from around the web, collected and curated for your reading.</p>
<a href="">Get Access Now</a>
</article>
<img src="https://picsum.photos/500/500" alt="">
</div>
2
Answers
Set the grid row to the same height as the height of your grid-container and the image will not overflow.
I don’t have a proper explanation for why the max-height: 100% doesn’t work, but one workaround which gives cover as required is to explicitly set the height of the img element to 70vh.
That way the object-fit seems to know better what the dimensions of the item are and it implements the cover correctly.