A really simple responsive background image

Posted 3 years ago     4809      css responsive

If you'd like a responsive background image that scales down with the window size but won't scale past 100% of the source image's width you can use the CSS beolow.

html { height:100%; margin:0px; } body { height:100%; background: #e8e8e8 url(/path/to/image.png) center center no-repeat; margin:0px; padding:0px; }

replace 800px with whatever width your background image is - ~ 30px

@media only screen and (max-width: 800px) { body { background-size: 100%; } } @media only screen and (min-width: 801px) { body { background-size: auto; } }

Now when you resize your browser or view the site on a smaller device the background will scale down to suite the screen size. But if you scale the window back up and beyond the size of your image the background will stop scaling when it reaches 100% of it's own width or height.


Awesome, thanks for sharing Dean!

You need to be logged in to post comments.

Welcome to Snippet Repo!

Discover, share and save useful code snippets.

Join our community over over 2,000 members! Currently a 48% acceptance rate. Apply for membership →