Search code examples
htmlcssbackgroundmedia-queriessize

How do I make a background-image larger with a @media query?


I'd simply like my background image to become larger when I increase my viewport size to @media only screen /* Tablet */ and (min-width: 768px) {}.

I've tried background-size:; however that didn't work.

I then tried to use a different image file to apply the background-size:; too and still nothing.

How would I go about doing this?

HTML:

    <advert class="bg-righttoleft">
      <div class="title-shift">
        <h1 class="title text-style">bla bla bla</h1>
        <h3 class="title-shift-h3 text-style">bla bla bla</h3>
        <p class="title-shift-p">bla bla bla</p>
      </div>
      <div class="channel">
        <h3 class="chan-text">Review of the week</h3>
        <a href="https://www.youtube.com/channel/UC-6OW5aJYBFM33zXQlBKPNA">
        <img class="chan-img" src="./engadget.jpg" alt="Engadget logo"></a>
      </div>
    </advert>

CSS:

.container  {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 50px 340px 1fr 50px;
  grid-template-areas:
    "header"
    "advert"
    "main"
    "footer";
  text-align: center;
}

advert  {
  grid-area: advert;
  background: url(./mi-vr-5.jpg);
  background-position-x: 50%;
  background-position-y: 75%;
  background-size: 1000px;
}

@media only screen /* Tablet */
  and (min-width: 768px) {
    .container  {
      grid-template-columns: 1fr;
      grid-template-rows: 50px 340px 1fr 50px;
      grid-template-areas:
      "header"
      "advert"
      "main"
      "footer";
    }

    advert  {
      background: url(./mi-vr-5-tablet.jpg);
      background-size: 2000px;
      background-repeat: no-repeat;
      font-size: 0.9em;
    }
}

Solution

  • In order to scale up your background image you can use:

    background-size: width height;

    for example:

    background-size: 200% auto;

    Temani Afif also meant that the closing tag "}" of @media only screen /* Tablet */ and (min-width: 768px) is missing

    Here is my sample code:

    <div class="background"></div>
    
    .background{
      height: 200px;
      width: 600px;
      background-image: url('https://images.pexels.com/photos/1735092/pexels-photo-1735092.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500');
      background-position: center center;
      background-size: 1000px auto;
      background-repeat: no-repeat;
    }