Responsive background image


I am trying to create a background image, that when you resize the browser it get gets smaller on both sides equally.
Like these pictures:



I think it needs to be done with the background-attachment: fixed; but I cannot make it to work.

Does anybody knows better how to do it?


If you want an image that covers the viewport, maintains aspect ratio and doesn’t scroll with the document then you can do this.

body {
  background: url( no-repeat;
  background-attachment: fixed;
  background-position:50% 50%;
  background-size: cover;

There are issues with fixed attachments on ios but there are work arounds if this is an issue.

If that’s not what you wanted then we may need to see a bit more detail and the code that you are applying.

1 Like

Yes this is not exactly what I want, it is making the image to be stretched.

Basically I want the image to be full on it’s dimensions, when the screen is on the same size, and gets shrinked on the sides when the screen gets smaller.

Does this makes sense ?

Ok I found the solution using these:

background-image: url(../images/bg.png)
background-position: center
background-repeat: no-repeat
background-size: cover

If anybody want it.

And the image is stretching if it gets bigger than the initial size, and when the browser is getting smaller it shrinks from both sides equaly.

:slight_smile: :slight_smile: :slight_smile:

That’s the same as the code I gave you except it’s not attached to the viewport ? The basics are the same.

The background-size: cover (which I I suggested to you) makes the image maintain its aspect ratio and will increase both width and height uniformly until the image covers the area required.

This effectively means one or other dimension will be cropped at some point unless the area is exactly the same aspect ratio as the image.

It’s not stretching the image, it’s maintains the aspect ratio the same as the code you are using. The image will shrink and enlarge uniformly with the viewport.

1 Like

Yes I was doing some mistakes too with the code, it’s pretty much the same as yours and it helped me!

I just wanted to mention that I made it without the fixed background, which I thought it was necessary in the beginning and in some cases it is indeed!

Thank you very much!!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.