I am encountering a problem with making my background image responsive, specifically on screens with a width of 768 pixels or less. The background image appears to be getting cropped more and more as I resize the screen to smaller widths.
body {
background-image: url('./img/moods.jpg');
background-size: cover;
background-repeat: no-repeat;
}
I have tried using the background-size: cover; property to ensure the background image covers the entire viewport, but the issue persists. I’ve reviewed various examples and tutorials, and most of them suggest the same approach.
What I’ve Tried:
I have experimented with different values for background-size and attempted to use media queries to address the problem, but none of my attempts have provided a satisfactory solution.
2
Answers
To make the background image responsive and prevent it from getting cropped on smaller screens, you can use the
background-position
property. By setting it tocenter
, the background image will be centered on the screen and won’t get cropped as the screen size decreases. Here’s an updated CSS snippet:css
This should help maintain the aspect ratio of the background image and ensure it is fully visible on screens with a width of 768 pixels or less.
If you insist on displaying the complete background image and at the same time have it cover the whole screen, you can use
background-size: 100% 100%;
.However, in most cases this will distort the image, so this only useful for abstract graphics, definitely not for photos.
Keep in mind that most mobile devices have a higher height than width (= "portrait") as opposed to desktop and laptop screens where you have the opposite situation ("landscape"). If you can use the same photo for both when using
background-size: cover
will depend on the photo itself. Usingbackground-position: center
can help here if the main motive of the photo is in its center and there is less important content around it, but not always. (note also @CBroes comment to your question)