'How to fit a image into css-grid without stretching
Problem:
The IMG is stretching the css-grid, and I want the image to scale-down and fit into the grid.
Tried: I have tried setting a max-height/width on the image, but it only reduces the stretching of the image.
.grid-container {
display:grid;
grid-template-areas:
"nav_bar"
"main"
"about"
"port_over"
"resu_proj"
"links";
background-color: #161616;
grid-row-gap: 5em;
}
/*Nav bar grid*/
.nav_bar {
display: grid;
grid-area: nav_bar;
grid-template-areas: "nav_img nav_links nav_links nav_links";
}
/*Nav bar img*/
.nav_img {
grid-area: nav_img;
object-fit: cover;
background-color: grey;
}
<div class="grid-container">
<div class="nav_bar">
<img src="./MLW_IMAGES/M.L.W logo.png" class="nav_img">
<div class="nav_links">
<nav>
<a href="/index.html#about">About</a>
<a href="/index.html#portfolio">Portfolio</a>
<a href="/index.html#contact">Contact</a>
</nav>
</div>
</div>
...
</div>
Solution 1:[1]
Take one class for only image. Give particular height and width to image class and give below css to image.
.class-name img {
max-height: 100%;
min-height: 100%;
min-width: 100%;
max-width: 100%;
object-fit: cover;
}
Solution 2:[2]
You can try setting max-height and max-width and specify a width you want the image to take if the image size is larger. is this what you are expecting ?
.grid-container {
display:grid;
grid-template-areas:
"nav_bar"
"main"
"about"
"port_over"
"resu_proj"
"links";
grid-row-gap: 5em;
}
/*Nav bar grid*/
.nav_bar {
display: grid;
grid-area: nav_bar;
grid-template-areas: "nav_img nav_links nav_links nav_links";
}
/*Nav bar img*/
.nav_img {
grid-area: nav_img;
object-fit: cover;
background-color: grey;
}
img
{
max-height:100px;
max-width:100px;
}
<div class="grid-container">
<div class="nav_bar">
<img src="https://dummyimage.com/50x50/000/fff" class="nav_img">
<div class="nav_links">
<nav>
<a href="/index.html#about">About</a>
<a href="/index.html#portfolio">Portfolio</a>
<a href="/index.html#contact">Contact</a>
</nav>
</div>
</div>
...
</div>
Solution 3:[3]
In responsive context:
img {
width: 100%;
height: auto;
}
/* grid */
.grid-element img {
min-height: 100%;
min-width: 100%;
object-fit: cover;
}
Solution 4:[4]
Add style "align-items: start"; to the grid container.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S. Rieger |
| Solution 2 | strek |
| Solution 3 | S. Rieger |
| Solution 4 | Daniel Msanii |
