简体   繁体   中英

Applying margin to a background image with fixed position

I have a background image that I want to cover my entire screen minus the header. I also don't want my background image to scroll. It should not move as the user scrolls over content.

For this reason I use the following to place my background:

    <div
      className={style.app}
      style={{
        backgroundImage: `url(${HomePhoto})`,
        backgroundRepeat: "no-repeat",
        backgroundAttachment: "fixed",
      }}
    ></div>

I am attempting to add additional CSS properties to assume the proper height and width are used:

    height: 100vh;
    width: 100vw;
    margin-top: 4rem;
    background-size: 100% 100%;

However the margin-top is not applied unless I remove backgroundAttachment: "fixed" . Is there a way I can achieve both styles?

You can use the backgroundPosition property which allows you to move a background image around in its container: https://developer.mozilla.org/en-US/docs/Web/CSS/background-position

<div
  className={style.app}
  style={{
    backgroundImage: `url(${HomePhoto})`,
    backgroundRepeat: "no-repeat",
    backgroundAttachment: "fixed",
    backgroundPosition: "100px 0", // or vh
  }}
></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM