CSS How to keep the section filled with a background image after the position transform

Viewed 36

I wanna keep the section filled with a background image after the position transform. Using this code I get a white background from the body element.

<section><div class="firstpage"></div></section>

   .firstpage{
       position: absolute;
       background-image:url('https://i.ibb.co/HGSY9Rv/bcb.png');
       background-attachment: fixed;
       background-position: center;
       background-repeat: no-repeat;
       background-size: cover;
 height:100%;
 width:100%;
     }



  $(".firstpage").mouseenter(function(){
$(".firstpage").animate({
 'background-position-x': '-200px',
});});

  $(".firstpage").mouseleave(function(){
$(".firstpage").animate({
 'background-position-x': '0px',
});});

https://codepen.io/gamegame/pen/NWMpJvy

1 Answers

make the bg image bigger in the width by using a calculation

the calculation is created by using native CSS calc()/var()

basically, we add the length of the animation to the width
so it will always overflow,
and this is correct since we have a calc() (so it is responsive)

so the animation works fine always bigger and smaller display

100% + 200px

(let's say if the width of your device is 550px, now this calcolation will be 550 + 200 = 750)

and there isn't any need for javascript for animation

because with :hover we can do the same / and transition

code example:

body {
  margin: 0;
  overflow:hidden; /* for not see the scrollbar */
}

.firstpage {
  --x: 200px;
  position: absolute;
  background-image: url("https://i.ibb.co/HGSY9Rv/bcb.png");
  /* not use `attachment: fixed` here */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: calc(100% + var(--x));
  transition: background-position-x 0.5s ease-in-out;
}

.firstpage:hover {
  background-position-x: calc(var(--x) * -1); /* 200px * -1 = -200px */
}
<section>
  <div class="firstpage"></div>
</section>

Related