CSS Background Image Change
A div or web page can have its background image changed with the CSS @media
code.
The background image may be switched when the browser width changes — when a phone's orientation is changed for example or when a person on a computer manually adjusts the width of their browser. The background image can also be changed when the page is printed.
No JavaScript is required.
An example is an ad for an app. If the ad is displayed in a browser larger than a certain width, the background is an image suggesting a laptop or desktop computer. When the ad is displayed on a narrower screen, the background image may be one suggesting a cellphone.
Another example is to swap out an elaborate background image to a plain white image or no image at all for printing the page.
In essence, it works like this.
When the page is loaded, this is the default (as an example).
#divid { background-image:url("http://example.com/image1.jpg"); }
When the screen width is, or becomes, less than 500px, the image is switched.
@media screen and (max-width:500px)
{
#divid { background-image:url("http://example.com/image2.jpg"); }
}
Here is a working installation. When the screen is 500 pixels wide or wider, the background image is the Willmaster logo. When the screen is under 500 pixels wide, the image is a small cartoon quote balloon. Both background images appear in the top-left part of the screen.
The example removes the background image when the web page is printed.
Here is the CSS:
#article-demo { background-image:url("https://www.willmaster.com/images/wmlogo_icon.gif"); } @media screen and (max-width:500px) { #article-demo { background-image:url("https://spamfreeform.com/images/SFF-icon-35.png"); } } @media print { #article-demo { background-image:url(); } }
The URLs in parenthesis are the URLs to the images in the div. The @media print
has no URL in the parenthesis which removes the image during printing.
The Divs with Background Images Willmaster Library article contains information about positioning background images within a div.
When you need to switch (or remove) a background image depending on screen width or page printing, it can be done with the CSS @media
code.
This article first appeared with an issue of the Possibilities newsletter.
Will Bontrager