Home > Software engineering >  How to make the background image fix in all different screen sizes and not move from its spot?
How to make the background image fix in all different screen sizes and not move from its spot?

Time:12-11

enter image description here

See these two circles, one is in the top left-hand corner and the other is in the bottom right-hand corner. Both circles are two different background images. I want both of them to stay at these spots and not move in all different screen sizes, including phones and tablets. I added a few media queries here and there, but it's not the best way to do it. If anyone can tell me how to achieve it, that would be great.

Link to the github repo

body {
    background: hsl(185, 75%, 39%);
    background-image: url(./assets/bg-pattern-top.svg), url(./assets/bg-pattern-bottom.svg);
    
    background-repeat: no-repeat no-repeat;
    background-position: -30% 1000%, 120% -1000%;
    font-family: 'Kumbh Sans';
}


@media(max-width: 1350px){
    body {
        background-position: -100% 1200%, 210% -1000%;
    }
}
@media(max-width: 1170px){
    body {
        background-position: -200% 1400%, 320% -1200%;
    }
}
@media(max-width: 1040px){
    body {
        background-position: -800% 1400%, 990% -1200%;
        background-attachment: fixed;
        
        
    }
}
@media(max-width: 980px){
    body {
        background-position: -25000% 1400%, 26000% -1200%;
        background-attachment: fixed;
    }
}

Note I'm using Tailwind in the overall designing, but still used Vanilla CSS to design the background image.

CodePudding user response:

It looks as though you want the radius of the circles to be something like 60vmin (ie 60% of the shortest side - in your image the sides are equal but you need to cater for keeping the circles circular when your user is in portrait or landscape modes).

This snippet positions the images so their centers are at the top left and bottom right of the body always.

body {
  width: 100vw;
  height: 100vh;
  background: hsl(185, 75%, 39%);
  background-image: url(https://picsum.photos/id/1015/300/300), url(https://picsum.photos/id/1015/300/300);
  background-size: 120vmin 120vmin, 120vmin 120vmin;
  background-repeat: no-repeat no-repeat, no-repeat no-repeat;
  background-position: -60vmin -60vmin, calc(100vw - 60vmin) calc(100vh - 60vmin);
  margin: 0;
}

CodePudding user response:

To keep your background image fixed, you have to use background-attachment property with the value Fixed. Values of background-attachment property: Scroll: It is the default value for the background-attachment property. ... Fixed: The background image will not scroll.

  • Related