How to responsive background image css

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The purpose of this article is to set a Responsive Full Background Image Using CSS.

    To set a Responsive Full Background Image using CSS we will use the CSSbackground-size property that has a value auto that tells the browsers to automatically scale the image’s width and height based on the container, to make element centered. And for small-size devices, we will add media queries that decrease the size of the image file to load fast.

    Syntax:

    background-size: auto; 

    Example:

    HTML

    Output:


    • 21 min read
    • Mobile, CSS, Responsive Design, Media Queries

    With all the talk of new HTML5 standards such as the srcset attribute and element, as well as server-side techniques such as Responsive Web Design + Server Side Components [RESS], you’d be forgiven for concluding that simple, static websites can’t support responsive images today.

    Editor’s Note: This article features just one of the many, suboptimal solutions for responsive images. We suggest that you review different approaches before choosing a particular responsive image solution, including these two: How To Avoid Duplicate Downloads In Responsive Images and Choosing A Responsive Image Solution.

    With all the talk of new HTML5 standards such as the srcset attribute and element, as well as server-side techniques such as Responsive Web Design + Server Side Components [RESS], you’d be forgiven for concluding that simple, static websites can’t support responsive images today. That conclusion might be premature, however. In fact, there’s an easy, straightforward way to deliver responsive images that’s supported by all of today’s Web browsers: A CSS background image.

    Further Reading on SmashingMag: Link

    • Automatically Art-Directed Responsive Images? Here You Go.
    • Responsive Images Now Landed In WordPress Core
    • Leaner Responsive Images With Client Hints

    However, the approach has some limitations, and it doesn’t work in all cases. But if your requirements aren’t complicated, and if you’re willing to make an extra effort to ensure your images are accessible, CSS background images may be all you need.

    More after jump! Continue reading below ↓

    In this article we’ll look at the CSS background approach in several steps:

    1. First, we’ll review the goals and requirements for responsive images.
    2. Then we’ll see how CSS media queries can help identify important characteristics of our users’ devices.
    3. We’ll explore the key CSS background-image property that lets us respond to those characteristics.
    4. We’ll look at a strategy for optimizing the individual images that make up a responsive set.
    5. We’ll examine the limitations of this approach; in many cases there are simple techniques to overcome them.
    6. And finally, we’ll describe the problems with this approach for which there are no workarounds.

    Note: This approach requires explicit control of your website’s style sheets as well as its HTML markup. If your website relies on a content management system [CMS], you might not have enough control over those aspects of the website.

    The Need For A Responsive Background Image

    Responsive images are an important component of responsive Web design [RWD], a design strategy developed by Ethan Marcotte to cope with the amazing popularity of mobile devices for viewing the Web. Ethan recognized that the previous best practice — developing separate websites for different types of devices — simply couldn’t cope with the astonishing variety of devices Web users might employ to access the websites we build.

    RWD takes a completely different approach: create a single website but let that website recognize and respond to its context. If the user has a desktop browser with a wide screen, for example, allow the website content to spread across multiple columns. On a smartphone, however, rearrange the content to confine it to a single column.

    In many cases, that’s where responsive design stops — simple adjustments to layout and presentation. If that’s all we consider, however, we’re not honoring the goal of responsive design, and we’re selling our users short.

    Truly responding to users’ context requires a design that considers all aspects of the experience, and that often includes images. For a real life example, consider a website such as contfont.net. That single page website has one main image and a typical set of HTML, style sheets, fonts, and JavaScript files.


    Resource Type Compressed Size
    Main page HTML 6 KB
    Style sheet CSS 10 KB
    Fonts Web Font 221 KB
    Scripts JavaScript 21 KB
    Supporting images Image 48 KB
    Main site image Image ??

    The website looks gorgeous on computers with super–high-resolution displays because it includes a high-resolution version of the main image. Delivering that image file doesn’t come cheap, though; its 1940 × 1229 pixels make the image 446 KB in size after compression.

    The website could use that same image file for all users without compromising the visual experience. Web browsers on smaller devices such as smartphones would resize it to fit the display. While that approach would preserve the visual appeal of the website, the overall user experience would suffer significantly.


    On an iPhone, a 290 × 183 pixel image that is 18 KB in size looks identical to the 452 KB, 1940 × 1229 pixel image on the MacBook Pro. Larger view.

    What does that mean for a user browsing to the website on, say, an earlier generation smartphone? For that user, a 290 × 183 pixel image that is 18 KB in size looks identical to the larger version. Without a responsive image approach, the website would force the user to download an extra 429 KB of data that is completely wasted. This excess is not just academic; it has a substantial effect on the website’s load time. The smartphone user may be accessing the website over a typical 3G connection at 2 Mb/s. Failing to deliver a responsive image increases the load time from 1.3 seconds to 3 full seconds, significantly more than doubling it!


    The full size image takes 3.0 seconds to load over a 3G network, compared to 1.3 seconds for a responsive image. Larger view.

    The primary goal for a responsive image approach is simple: deliver only the pixels that the user’s device can actually use.

    Identifying The User’s Context

    If our websites are going to respond to our users’ context, we need a way to identify that context. Today, CSS offers the most effective way to distinguish different devices. CSS gives us the answers to two critical questions: what is the size of the user’s display? And does the display support Retina-style images?

    The CSS tool that gives us this information is a media query. Media queries define a set of CSS style properties that apply only to devices with specific qualities. Originally, media queries were limited to media types. The CSS specification defines a large number of them including, for example braille [for braille tactile feedback devices], speech [for speech synthesizers], tty [for devices with only monospaced fonts, such as teletypes] and tv [for television-type devices with low resolution and no scrolling]. Currently, the only two media types that most browsers support are print [for printed, paged material] and screen [for computer screens].

    CSS3 expanded the use of media queries, however, by allowing style sheets to specify specific features of devices as well as the media type. And in the case of screen devices, the features can include many characteristics of the display, including its width, orientation, resolution and pixel ratio. Those features provide just the information we need to select an appropriate responsive image.

    Here’s how media queries can help us solve the dilemma of the previous section. As an example, a 15-inch MacBook Pro has a screen width of 1440 pixels [ignoring for the moment the Retina display option]. To identify styles that apply to screens of this size [and larger], we can write our style sheet as:

    @media only screen and [min-width: 1440px] {
        /* styles for MacBook Pro-sized screens and larger */
    }
    

    Any styles defined in that block will only apply when the user accesses the Web page using a device with a screen size of 1440 pixels. There’s a catch, though. The media screen size doesn’t apply to the device’s hardware; rather, it applies to the Web browser’s viewport. The viewport is the size of the browser window after subtracting any browser chrome, such as toolbars.

    Unless the user is browsing in full screen mode, the browser window will actually be somewhat less than 1440 pixels in width. For this more common case, therefore, we might want to rewrite the style sheet a bit. Perhaps 1200 pixels is more realistic.

    @media only screen and [min-width: 1200px] {
        /* styles for wide screens */
    }
    

    The media query has two parts. The first part, only screen, indicates that the styles shouldn’t apply to printed copies of the page or other non-standard devices. [The only keyword doesn’t actually affect the media query; it’s there strictly for really old browsers that don’t support media features. Because those browsers don’t understand the only syntax, they’ll simply ignore the entire block of styles.] The second part of the query, min-width: 1200px, gives the minimum screen width at which the styles will be applied. The and that joins those parts means that both must be true for the styles to apply.

    We can use a similar technique to define styles for portrait-mode smartphones.

    @media only screen and [max-width: 320px] {
        /* styles for narrow screens */
    }
    

    In this case we can go ahead and use the actual device screen size in the query. Web browsers on smart phones are always full-screen width.

    The min-width and max-width feature specifications make it easy to determine the width of the user’s device. Unfortunately, identifying a Retina display isn’t quite as straightforward. Different browsers use different syntaxes for this feature, so we must resort to vendor prefixes. To make things slightly worse, many versions of Firefox had a bug in their syntax, so we need to use both a fixed and a “broken” syntax for Mozilla browsers. As of now, the recommended query for Retina-quality displays looks like the following.

    @media
    only screen and [-webkit-min-device-pixel-ratio: 2],
    only screen and [min--moz-device-pixel-ratio: 2],
    only screen and [-moz-min-device-pixel-ratio: 2],
    only screen and [-o-min-device-pixel-ratio: 2/1],
    only screen and [min-device-pixel-ratio: 2],
    only screen and [min-resolution: 192dpi],
    only screen and [min-resolution: 2dppx] {
        /* styles for Retina-type displays */
    }
    

    Eventually browsers will all support the standard dots per pixel notation [dppx] and we can drop the vendor prefixes from our style sheets.

    The CSS Background-Image Property

    If CSS can reliably identify a user’s context, you might think it would be easy to support responsive images. One approach that might seem logical would be to set display: none for those images we don’t wish to download. Here’s an attempt based strictly on screen size. [We’re omitting Retina considerations for brevity.]

    
    
        
            
            
            
            img.smallscreen { display: none; }
            @media only screen and [max-width: 320px] {
                img {
                    display: none;
                }
                img.smallscreen {
                    display: inline;
                }
            }
            
        
        
            
            

    Bài mới nhất

    Chủ Đề