Text in Responsive Background Image Overflow
In this code, I want the text / div to not go beyond the image vertically when viewing it in mobile. Due to the Parent height, it overflows the image. How can I solve this problem? (On Desktop, it looks fine.)
6 Replies
i think you're looking for background-size: cover
Sorry for the very late response, let me try doing that
Ohh yes it does work! But the image gets cropped. I actually like this more than my original idea, but just out of curiousity, how do I keep the aspect ratio / prevent it from cropping, for a lack of better word?
You really can’t. You can bloat up your code with a bunch of different sizes of the image in the html /then use grid to overlay the text. but background images are decorative. The text/information is always most important. Images will either stretch to fit or we use cover and it crops. It’s a bummer and you can try to move around to get the focal point you want with background position but thinking about an image , you can’t make it responsive and keep it the same dimensions.
If you have it on a screen and want it to take up the whole viewport width, it has to be cropped down to work on huge screens that are wider than taller then small phones that are taller than they are wider; or it has to stretch. Think about how all those little pixels are supposed to take up that space and how that behaves when it gets wider or thinner/longer. Background size and object fit of cover is a godsend but yes we sacrifice either way.
How are you taking up the space with the background image? Did you set a height ? If so, you’re likely going to overflow. You want to optimize your image size (don’t just bring it some huge image from i splash), set height with your content and padding. Can you post a link to your codepen or git repo?
Edit: check out this video for some good information that will be helpful
https://youtu.be/zHZRFwWQt2w?si=konIGHppW7W5oq6x
Kevin Powell
YouTube
Background images with HTML & CSS
In this video, I look at how to set a background image, problems people run into with them and how to fix them, and finish things off with a bonus tip on readability.
🔗 Links
✅ How to select things in your CSS: https://www.youtube.com/watch?v=JVsI0fspik8&list=PL4-IK0AVhVjM0xE0K2uZRvsM7LkIhsPT-&index=9
✅ Why you should use Firefox when learn...
Sorry for the really late response, but thank you! I'll take a gander at the video!