Search code examples
htmlcsscss-gridimage-resizing

How to make an image fit the browser window using grid?


I want to fit a picture into a website that still works when you scale it, but my picture is gigantic and I can't seem to make it fit. I tried to put a restriction on the wrapper div (here called "innpakning") on the picture itself, and the surrounding div. Nothing seems to work. And even if I could get it to work, that would defeat the purpose as I want it to scale to the website window. How do I make it fit the window?

I tried using

max-width: 100%;
max-height: 100%;

and it fixed the image, but not the spacing of the rest of the website. I end up with an enormous gap between .overskrift and .innhold.

<body>
  <div class="innpakning">

    <div class="overskrift">
      <p id="text"> Hvaler </p>
    </div>

    <div class="innhold">

      <div class="meny">


        <div class="alt"><a href="minnettside.html"> Info</a> </div>
        <div class="alt"><a href="minnettside2.html">Bilde </a> </div>
        <div class="alt"> <a href="minnettside3.html">Lyd </a> </div>
        <div class="alt">  <a href="minnettside4.html">Video</a>  </div>
      </div>

      <div class="faktisk">
<img src="css/media/hval.jpg" alt="">

      </div>
    </div>

  </div>
</body>
innpakning{
  margin: 20px;
  padding-left:  10px;
  padding-right: 10px;
  display: grid;
  grid-template-rows: 1fr 1fr;
}
.overskrift{
  background-color: none;
  color: black;
  font-weight: bold;
}
.innhold {
background-color: #29648A;

}
.meny {
  background-color: none;
  display: grid;
  margin: auto;
  grid-template-columns: 1fr 1fr 1fr 1fr;
}
 a {
  text-decoration: none;
  margin-left: 25px;
  color: white;
}
.alt {
  color: #FAFAFA;
  text-decoration: none;
  background-color: #25274D;
  color: white;
  padding: 10px;
  margin: 2px;
}
.alt:hover {
  background-color: #464866;
}
img {
  margin-left: auto;
  border: solid black;
  max-width: 100%;
  max-height: 100%;
}
.faktisk {
color: #DEDEDE;
padding: 15px;
margin: auto;
display: grid;
grid-template-columns: 1fr
}
@import url('https://fonts.googleapis.com/css?family=Asset');
#text {
    font-family: Asset, cursive;
    text-align: center;
    font-size: 35px;
    color: rgba(245, 246, 255, 0.96);
    background-color: rgba(168, 168, 168, 0.11);
    text-shadow: rgba(0, 0, 0, 0.99) 2px 2px 2px;
}

Solution

  • I suggest that you use the CSS unit type vw to set the max-width of the image, like so:

    img {
      margin-left: auto;
      border: solid black;
      max-height: 100%;
      max-width: 100vw;
      height: auto;
    }
    

    Read more at MDN: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#Numbers_lengths_and_percentages