Search code examples
cssimageimage-scaling

How do I fit an image inside of this specified grid space?


I'm trying to fit an image inside of the grid area that I've specified but everything I've tried isn't giving me the result I want.

I want the image to fill the space without cropping the image. Is that possible?

Result of Code below: https://i.sstatic.net/RTxh1.jpg

Original Image I would like to fit: https://i.sstatic.net/GoLYl.jpg

body{
     width: 100vw;
     height: 100vh;
     color: black;
     margin: 0;
     padding: 0;
     font-family: poppins, sans-serif;
     }
.container{
     display: grid;
     grid-template-columns:repeat(5, 1fr);
     grid-template-rows: 0.5fr 3fr 1fr;
     height: 100vh;
     }
.image{
     background-image: url(./assets/header_img.jpg);
     width: 100%;
     height: 100%;
     grid-area: 1/1/3/-1;
     object-fit: fill;
     background-repeat: no-repeat;
 }


 

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Link your CSS stylesheet -->
    <link rel="stylesheet" href="index.css">
    <link rel="preconnect" href="https://fonts.gstatic.com"> 
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500&display=swap" rel="stylesheet">
</head>
<body>
  <div class="container">
    <div class="nav">nav</div>
    <div class="image">image</div>
    <div class="content">content</div>
    <div class="footer">footer</div>
  </div>


Solution

  • You could add background-size: 100% 100%; and it will fill it comletely without cropping it. Though it will stretch the image to fit the grid.

    See here:

    body{
         width: 100vw;
         height: 100vh;
         color: black;
         margin: 0;
         padding: 0;
         font-family: poppins, sans-serif;
         }
    .container{
         display: grid;
         grid-template-columns:repeat(5, 1fr);
         grid-template-rows: 0.5fr 3fr 1fr;
         height: 100vh;
         }
    .image{
         background-image: url(https://i.imgur.com/c3jpM7D.jpeg);
         background-size: 100% 100%;
         width: 100%;
         height: 100%;
         grid-area: 1/1/3/-1;
         object-fit: fill;
         background-repeat: no-repeat;
     }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <!-- Link your CSS stylesheet -->
        <link rel="stylesheet" href="index.css">
        <link rel="preconnect" href="https://fonts.gstatic.com"> 
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500&display=swap" rel="stylesheet">
    </head>
    <body>
      <div class="container">
        <div class="nav">nav</div>
        <div class="image">image</div>
        <div class="content">content</div>
        <div class="footer">footer</div>
      </div>