Css - how to stop image scalling with size cover?

2019-08-01 19:56发布

问题:

I'm creating simple media for screens over 2560px in width. My problem is that I have header and over 2600px I set static width to my header, when I resize window over 2600px header have 2600px width but image is resizing. How to set image size relative to header width, not to screen width??

#header {
  position: relative;
  height: 100vh;
  .background-image {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-image: url('~/images/17.jpg');
    background-size: cover;
    background-attachment: fixed;
    filter: brightness(50%);
    -webkit-filter: brightness(50%);
  }
}
@media only screen and (min-width: 2600px) {
  #header {
    width: 2600px;
    margin: 0 auto;
    height: 1000px;
    .background-image {
      width: 2600px;
    }
  }
}

回答1:

The problem is with background-attachment: fixed; which causes the background to scale with the viewport. According to MDN,

The background is fixed relative to the viewport. Even if an element has a scrolling mechanism, the background doesn't move with the element. (This is not compatible with background-clip: text.)

And neither is it compatible with background-size: cover, apparently.

Solution: reset the background-attachment in the media query.

Here is a codepen with the solution.
Or, for people who prefer snippets, a snippet (only with the SCSS compiled).

body {
  margin: 0;
}

#header {
  position: relative;
  height: 100vh;
}
#header .background-image {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-image: url("https://placehold.it/900x300");
  background-size: cover;
  background-attachment: fixed;
  filter: brightness(50%);
  -webkit-filter: brightness(50%);
}

@media only screen and (min-width: 600px) {
  #header {
    width: 600px;
    margin: 0 auto;
    height: 190px;
  }
  #header .background-image {
    background-attachment: initial;   /* new */
  }
}
<section id="header">
  <div class="background-image">
    hello
  </div>
</section>

Note that I changed the sizes a bit to allow me to test; the breakpoint is now at 600px rather than 2600px, since I don't have that wide a monitor. So you don't have to copy the whole code, the new line with the background-attachment is enough.



回答2:

I would use:

.background-image {
    width: 2600px;
    background-size: initial;  /* to use the file sizes default height/width */
    background-position: center;  /* then optionally center the image */
}

Since .background-image has the same width as #header, your next obstacle would be the image's height hence the possible need for centering.