HTML and CSS Reference
In-Depth Information
Controlling Background Images with Media Queries
As long as the background-image property is defined in a rule controlled by a media query, most browsers will
download the image only if they match the conditions in the query. For simplicity, I'll use @media rules in the
following example, but the styles could be in separate style sheets attached with media queries. This is how to
send different background images to devices depending on their width:
#header {
background-color: #D2E1E6; /* light blue */
background-image: none;
background-repeat: no-repeat;
}
@media only screen and (max-width: 480px) {
#header {
background-image: url(../images/header phone.jpg);
}
}
@media only screen and (min-width: 481px) and (max-width: 768px) {
#header {
background-image: url(../images/header tablet.jpg);
}
}
@media only screen and (min-width: 769px) {
#header {
background-image: url(../images/header desktop.jpg);
}
}
In this example, the background-image property is set to none in the basic style. But even though there's no
image, background-repeat is set to no-repeat . This avoids the need to repeat the same property in each of the
media queries. Only the value of background-image is overridden, serving up three different images.
Consider carefully whether a decorative background image is really needed for the smallest mobile devices.
Although it's important for a site to look attractive on a mobile phone, users won't thank you for using up their
precious data allowance with a lot of unnecessary eye candy.
Tip
Controlling Images Embedded in the HTML
Media queries give you far less control over images embedded in <img> tags. In Chapter 7, “Making the Images
and Captions Adapt to the Screen Width” described how to resize an image dynamically for a responsive web
design. The technique involves removing the width and height attributes from the HTML, and wrapping the
image in a <div> or <figure> element. Then you can use CSS to set the outer element's width to a percentage, and
give the image a maximum width of 100% .
The styles in the Mediterranean Destinations examples since Chapter 7 float the image container left or
right. In a responsive design using media queries, you could center the image container and give it a maximum
width in the basic styles, and float it only when the screen is wider like this:
.figure {
max-width: 400px;
}
 
 
Search WWH ::




Custom Search