banner



How Do You Get A Background Image To Center Across All Media Break Points

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

Quick summary ↬ With all the talk of new HTML5 standards such as the srcset attribute and <picture> element, as well as server-side techniques such equally 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 Annotation: This commodity features simply one of the many, suboptimal solutions for responsive images. We suggest that you review different approaches earlier choosing a detail 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 <motion picture> chemical element, as well every bit server-side techniques such equally Responsive Web Blueprint + Server Side Components (RESS), you'd be forgiven for concluding that simple, static websites can't support responsive images today. That determination might be premature, however. In fact, in that location'due south an easy, straightforward way to deliver responsive images that'south supported by all of today'southward Web browsers: A CSS background image.

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

Withal, the arroyo has some limitations, and it doesn't work in all cases. But if your requirements aren't complicated, and if you're willing to brand an extra effort to ensure your images are accessible, CSS groundwork images may be all you lot need.

More subsequently jump! Go on reading below ↓

In this article we'll look at the CSS groundwork approach in several steps:

  1. Starting time, nosotros'll review the goals and requirements for responsive images.
  2. Then nosotros'll see how CSS media queries tin can assist identify of import 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 private images that make up a responsive set.
  5. We'll examine the limitations of this arroyo; in many cases there are simple techniques to overcome them.
  6. And finally, we'll describe the problems with this arroyo for which there are no workarounds.

Note: This arroyo requires explicit control of your website'southward way sheets as well as its HTML markup. If your website relies on a content management system (CMS), you lot might not take enough control over those aspects of the website.

The Demand For A Responsive Background Epitome

Responsive images are an important component of responsive Spider web blueprint (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 amazing variety of devices Spider web users might employ to access the websites we build.

RWD takes a completely unlike approach: create a single website but allow 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 blueprint stops — simple adjustments to layout and presentation. If that'southward all we consider, notwithstanding, we're not honoring the goal of responsive blueprint, and we're selling our users short.

Truly responding to users' context requires a pattern that considers all aspects of the experience, and that often includes images. For a real life case, 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.


Resources Type Compressed Size
Main page HTML 6 KB
Way sheet CSS 10 KB
Fonts Web Font 221 KB
Scripts JavaScript 21 KB
Supporting images Paradigm 48 KB
Main site epitome Image ??

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

The website could utilize that aforementioned prototype file for all users without compromising the visual experience. Web browsers on smaller devices such equally smartphones would resize it to fit the brandish. While that approach would preserve the visual appeal of the website, the overall user feel would suffer significantly.

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

What does that hateful 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 arroyo, the website would force the user to download an actress 429 KB of data that is completely wasted. This excess is not simply bookish; it has a substantial effect on the website's load time. The smartphone user may be accessing the website over a typical 3G connectedness at ii Mb/s. Failing to deliver a responsive image increases the load time from 1.3 seconds to 3 full seconds, significantly more 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.
The total size image takes 3.0 seconds to load over a 3G network, compared to i.3 seconds for a responsive prototype. Larger view.

The master goal for a responsive image approach is simple: deliver only the pixels that the user'southward device can really utilize.

Identifying The User'southward Context

If our websites are going to respond to our users' context, we need a manner to identify that context. Today, CSS offers the about effective way to distinguish different devices. CSS gives u.s. the answers to 2 critical questions: what is the size of the user'south brandish? And does the display back up 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), spoken communication (for speech synthesizers), tty (for devices with only monospaced fonts, such as teletypes) and tv (for idiot box-type devices with low resolution and no scrolling). Currently, the only ii media types that most browsers support are print (for printed, paged textile) and screen (for figurer screens).

CSS3 expanded the utilise of media queries, nevertheless, 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 brandish, including its width, orientation, resolution and pixel ratio. Those features provide just the data we need to select an appropriate responsive paradigm.

Here'southward how media queries tin can help united states of america 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 place styles that utilise to screens of this size (and larger), we tin write our style canvass as:

          @media just screen and (min-width: 1440px) {     /* styles for MacBook Pro-sized screens and larger */ }                  

Any styles defined in that block will simply utilize 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'due south hardware; rather, it applies to the Web browser's viewport. The viewport is the size of the browser window subsequently subtracting any browser chrome, such equally toolbars.

Unless the user is browsing in total screen fashion, the browser window will really be somewhat less than 1440 pixels in width. For this more mutual case, therefore, we might desire to rewrite the fashion sheet a bit. Perchance 1200 pixels is more realistic.

          @media but screen and (min-width: 1200px) {     /* styles for wide screens */ }                  

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

We can employ a like technique to define styles for portrait-manner smartphones.

          @media but 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 e'er full-screen width.

The min-width and max-width characteristic specifications make information technology like shooting fish in a barrel to decide the width of the user's device. Unfortunately, identifying a Retina brandish isn't quite every bit straightforward. Dissimilar browsers utilise unlike syntaxes for this feature, so nosotros must resort to vendor prefixes. To brand things slightly worse, many versions of Firefox had a bug in their syntax, so we demand to apply both a fixed and a "broken" syntax for Mozilla browsers. Every bit of at present, the recommended query for Retina-quality displays looks similar the following.

          @media only screen and (-webkit-min-device-pixel-ratio: two), merely screen and (min--moz-device-pixel-ratio: 2), merely screen and (-moz-min-device-pixel-ratio: 2), simply screen and (-o-min-device-pixel-ratio: 2/1), but screen and (min-device-pixel-ratio: ii), just screen and (min-resolution: 192dpi), merely screen and (min-resolution: 2dppx) {     /* styles for Retina-type displays */ }                  

Somewhen browsers will all support the standard dots per pixel note (dppx) and we can drop the vendor prefixes from our style sheets.

The CSS Groundwork-Image Property

If CSS tin can reliably identify a user's context, you might think information technology would be easy to back up responsive images. One approach that might seem logical would exist to set display: none for those images nosotros don't wish to download. Here's an attempt based strictly on screen size. (Nosotros're omitting Retina considerations for brevity.)

          <!DOCTYPE html> <html lang="en">     <caput>         <meta charset="utf-viii">         <title></title>         <style>         img.smallscreen { display: none; }         @media only screen and (max-width: 320px) {             img {                 display: none;             }             img.smallscreen {                 display: inline;             }         }         </style>     </head>     <trunk>         <img src="largeimage.jpg">         <img class="smallscreen" src="smallimage.jpg>     </body> </html>                  

The lawmaking higher up volition display the correct image based on the screen size; withal, the brandish: none property won't actually forbid browsers from downloading the hidden images. Smartphone browsers will download the large image even though it'due south never displayed. Unfortunately, this obvious approach doesn't accomplish the master goal for responsive images.

The trouble occurs considering browsers handle the HTML separately from the CSS. The HTML markup requests two prototype files, then the browser dutifully fetches both. Later, information technology parses the CSS styles just to discover that one of the images is not displayed, but past and then it's too late.

Our CSS media queries volition only work if nosotros tin use them strictly for CSS properties and not HTML content. That may seem incommunicable, just it turns out that there is a sneaky way to simply use CSS for imagery — the background-epitome belongings. Here'due south how we do that:

  1. In the HTML markup, don't include references to any epitome files. Instead simply employ empty <div> or <span> elements.
  2. Place an image in the empty <div> or <span> by setting its background-image holding.
  3. Use media queries to substitute the appropriate responsive images, depending on screen size and resolution.

Using these rules, we can modify the in a higher place case so that responsive images actually work correctly.

          <!DOCTYPE html> <html lang="en">     <head>         <meta charset="utf-8">         <title></title>         <style>         #prototype {             background-image: url(largeimage.jpg);         }         @media simply screen and (max-width: 320px) {             #paradigm {                 background-paradigm: url(smallimage.jpg);             }         }         </mode>     </head>     <body>         <div id="image"></div>     </body> </html>                  

That, in a nutshell, is how to support responsive images with CSS background images. Any real application will require a bit more lawmaking (for instance, we need some mode to indicate the image size). The boosted code, however, is standard CSS without whatsoever tricks.

Creating The Responsive Images

With an understanding of how to use responsive images, the next pace is actually creating the image variations. The original source image should have the highest resolution possible, at least as loftier as the near detailed image your website will deliver. (In the example of contfont.cyberspace, the source prototype is 3888 × 2592 pixels.) Your graphics program of choice should be able to resize that source prototype to fit your website'south breakpoints.

As long as y'all're working in your graphics plan, be sure to optimize even the high-resolution images as much as possible, for example, by using the lowest quality setting feasible for the image. Even users on loftier-resolution displays will appreciate the faster page load time. If the image is in JPEG format, you lot can also enable the progressive choice when you lot export it. This option lets the browser brandish a low-fidelity version of the prototype apace while it continues to download the total epitome.

When it comes to the breakpoints themselves, you shouldn't fall into the temptation of using the aforementioned breakpoints for your images as you're using for the website's layout. It'south rarely the case that the best layout breakpoints are also the best image breakpoints. Instead, optimize your image breakpoints for the image. Here's a strategy I like for finding the optimum paradigm sizes.

First make up one's mind the smallest resolution prototype that is practical for your website to evangelize. In the case of contfont.net, the smallest practical viewport size is 320 pixels, corresponding to a not-Retina iPhone in portrait orientation. (Devices with smaller viewports exist, and are likely to be in the futurity — smart watches, anyone? — merely those devices aren't likely to visit the website.) On the contfont.net website, a viewport size of 320 pixels leaves 290 pixels for the prototype width, then the lowest resolution image we need is 290 × 183 pixels. Accept your graphics program resize the source image to that size.

Next create a simple test folio for that image. Hither's the markup I use:

          <!DOCTYPE html> <html lang="en">     <head>         <meta charset="utf-viii">         <title></title>     </head>     <body>         <img src="examination.jpg" width="100%">         <p>Window size: <span id="size"></span> pixels</p>         <script>         window.onresize = function() {             document.getElementById("size").innerHTML = window.innerWidth;         };         </script>     </body> </html>                  

This folio displays the examination image and the current window size. Open it in your browser, and resize the browser window so that its width is about the size of your smallest breakpoint. Considering the test image matches this width, it should await fine.

Now slowly resize your browser window by increasing its width. As the width grows, the browser volition automatically interpolate and resize the epitome. As the amount of interpolation increases, the epitome quality suffers and, at some point, the image will look unacceptably poor. Annotation the screen width when that point occurs, as that screen width is your first breakpoint.

Resize your browser window until the width at which the image looks unacceptably poor. That screen width will be your breakpoint.
Resize your browser window until the width at which the paradigm looks unacceptably poor. That screen width will exist your breakpoint. Larger view.

When you've constitute the first breakpoint, employ your graphics program to create a new test prototype at that size from the original source. Repeat the procedure with the new exam epitome to discover the side by side breakpoint, and continue until you've reached the maximum viewport width your website volition back up.

At this point you'll have your image breakpoints and a set of images to lucifer. For Retina displays, create boosted images at double resolution. Here's the full list of images for the contfont.net website:

Paradigm File Resolution Size (no pinch)
candc290.jpg 290 × 183 nineteen,378 Bytes
candc290@2x.jpg 290 × 183 (Retina) 56,277 Bytes
candc538.jpg 538 × 341 52,914 Bytes
candc538@2x.jpg 538 × 341 (Retina) 159,867 Bytes
candc970.jpg 970 × 614 132,766 Bytes
candc970@2x.jpg 970 × 614 (Retina) 451,939 Bytes

You can use this approach separately for each prototype on your website, equally there'south no reason that all images have to use the same breakpoints. If your website has a lot of images, still, it might exist more efficient to find some common breakpoints using a few of the website's images and then repeat those breakpoints for all of the images on the website.

Overcoming Limitations

In the simplest cases, the steps to a higher place are all it takes to back up responsive images. Of class, websites are rarely that simple, and, indeed, there are several steps we can have to amend the arroyo.

Making Images Accessible

The standard <img> tag supports an alt attribute that provides an alternative, textual description of the prototype. That clarification is of import for accessible websites, as users with screen readers rely on the alt content to describe the image. CSS background images don't have an <img> tag and thus no alt attribute, just we can still make them attainable to vision-dumb users. To do that, we add two additional attributes to our markup.

          <div id="prototype" office="img" aria-label="Textual Clarification"></div>                  

The first extra aspect, role, lets screen readers know that the <div> is serving the part of an <img> tag, fifty-fifty though it's not explicit in the markup. The second aspect, aria-label serves the same purpose every bit an alt attribute in an <img>. With those two additions, screen readers can announce to their users that the element is an paradigm, and they will read the alternating text description that you've provided for that image.

Scaling Images in the Browser

In that location's some other helpful belongings of the <img> tag that our unproblematic approach doesn't support: automatic sizing and scaling past the browser. With a standard <img>, we can simply set the width every bit a percentage of the containing element and the browser automatically calculates the width and scales the meridian proportionally. For example, consider the fragment beneath displaying the prototype file image.jpg which has natural dimensions of 600 × 300 pixels.

          <div mode="width: 400px">     <img src="image.jpg"> </div>                  

The browser automatically fits the image into the containing <div>, reducing its width from 600 to 400 pixels. It besides preserves the prototype's attribute ratio, scaling the image height from 300 to 200 pixels at the same time. The result is an undistorted image that fits perfectly on the folio.

Cheers to an approach first described past Grady Kuhnline, we can achieve the same outcome with a CSS background image for modern browsers. (Warning: The arroyo this subsection describes does not work in Cyberspace Explorer version 8 and below, every bit those browsers don't back up the necessary CSS properties.)

The easiest function to tackle is scaling the width. As with the <img> tag we can set up our element within a <div> of fixed width; we just accept to explicitly indicate that the background should fill that <div>. The HTML markup doesn't await very different.

          <div style="width: 400px">     <span id="prototype"></span> </div>                  

We take to combine several CSS properties to gear up the width; let's take them one at a time:

  1. Set the display holding of the #image chemical element to inline-block. Without this property, CSS will display the <span> chemical element every bit inline and we won't be able to give it a width or (in a minute) a height.
  2. Set the width of that chemical element to 100% so that our prototype fills the containing <div>.
  3. Set the font-size and line-meridian properties to 0 and then that any contents inside the span don't gene into its size.
  4. Gear up the vertical-marshal property to middle to vertically center the prototype element in the containing <div>.
  5. Set the background-size belongings to 100% so our image fills the image chemical element.
  6. Ready the background-position holding to l% 50% to align the background image inside the prototype element.
  7. Fix the background-echo property to no-echo to foreclose the browser from tiling the image horizontally or vertically.

The resulting CSS sets the styles for the image chemical element (the <span> element with an id of "image").

          #image {     display: inline-block;     width: 100%;     font-size: 0;     line-superlative: 0;     vertical-align: middle;     background-size: 100%;     background-position: l% 50%;     groundwork-repeat: no-repeat;     background-image: url(image.jpg); }                  

Those steps have care of giving the image a width, merely we haven't yet tackled the tiptop. Nothing in the above markup or styles tells the browser the height of the image element. As a result, it will default to its natural height which is, alas, zip, every bit in that location is no actual content in the <bridge>. Fortunately, nosotros can fix that with a few pocket-size additions.

First we demand to add an extra <bridge> element to our markup. This extra element is placed inside the image element.

          <div mode="width: 400px">     <span id="image">         <span id="image-inner">         </bridge>     </span> </div>                  

Now we define a few style properties for this inner <bridge>.

  1. Set its display belongings to block so it will take a meridian and width.
  2. Prepare its height to 0 since it doesn't have whatsoever actual content.
  3. Add a padding-pinnacle property specifying a percentage equal to the pinnacle-to-width ratio of the image.

That final step is the key. Fifty-fifty though the <span> inherits no height from its content, padding-top forces the element to take upwards vertical space. Furthermore, the padding-top holding accepts per centum values where the percentage is relative to the element'due south width. Our image is 970 × 614 pixels, and so the percent value we use is (614 ÷ 970) × 100%, or 63.3%. Now the browser will ensure that our image maintains its aspect ratio as information technology's scaled upward or downwardly.

          #image-inner {     display: block;     height: 0;     padding-elevation: 63.3%; }                  

All Together Now

To encounter how all these components fit together, here is the code for the contfont.net website nosotros've used as an example. First is the HTML markup that includes the main website image.

          <div class="hero">     <span id="cafe" role="img" aria-label="Coffee and croissant.">         <bridge class="inner">         </bridge>     </span> </div>                  

The style sheet defines properties that make the prototype scale proportionally.

          .hero #cafe {     width: 100%;     display: inline-block;     vertical-align: middle;     font: 0/0 serif;     text-shadow: none;     color: transparent;     background-size: 100%;     groundwork-position: 50% 50%;     background-repeat: no-repeat; } .hero #cafe .inner {     padding-height: 63.35%; /* height/width of image */     display: block;     height: 0; }                  

And finally, a prepare of media queries choice the advisable image file based on the user's context. (The case below omits vendor prefixes for brevity.)

          /* default screen, non-retina */ .hero #cafe { background-image: url("../img/candc970.jpg"); }  @media only screen and (max-width: 320px) {     /* Small screen, non-retina */     .hero #cafe { background-image: url("../img/candc290.jpg"); } } @media only screen and (min-resolution: 2dppx) and (max-width: 320px) {     /* Small screen, retina */     .hero #buffet { background-prototype: url("../img/candc290@2x.jpg"); } } @media only screen and (min-width: 321px) and (max-width: 538px) {     /* Medium screen, non-retina */     .hero #buffet { groundwork-image: url("../img/candc538.jpg"); } } @media simply screen and (min-resolution: 2dppx) and (min-width: 321px) and (max-width: 538px) {     /* Medium screen, retina */     .hero #cafe { background-prototype: url("../img/candc538@2x.jpg"); } } @media only screen and (min-resolution: 2dppx) and (min-width: 539px) {     /* Large screen, retina */     .hero #cafe { background-paradigm: url("../img/candc970@2x.jpg"); } }                  

Potential Problems

CSS background images are a convenient way to deliver responsive images today, but the approach isn't perfect. At a basic level, it violates one of the key philosophies of modern Web standards — separating content from presentation. Advanced versions of the approach also suffer from browser compatibility concerns, and the approach doesn't address some of the deeper issues with responsive images in general.

Separation of Style and Content

CSS was developed specifically to separate style from content. On the modern web, HTML pages provide all of a website's content, while style sheets merely bear on the presentation of that content. Fashion sheets should not define the content itself. Of course, the separation between style and content has already been breached somewhat with the CSS content-before and content-subsequently properties, but those properties are typically used to enhance the presentation (for example, by adding an icon to an element).

Specifying principal website images with CSS is a dissimilar level entirely. By specifying master content with CSS rather than HTML, nosotros make our websites harder to troubleshoot, nosotros make them more hard to maintain and nosotros create barriers for systems that might try to parse our websites automatically.

Unfortunately, there actually is no getting around this problem. If strict separation of style and content is important to you, then you lot'll have to consider alternative approaches for responsive images.

Browser Support for Scaled Images

As noted above, the enhancements nosotros added to the basic approach for scaled images won't piece of work in Internet Explorer version 8 and beneath. Standardized approaches such equally srcset may be backwards compatible with such browsers, merely, of form, srcset itself isn't available on any mainstream browser today.

If you demand to support IE8 right now, you might consider creating a carve up way sheet for IE8 that specifies stock-still epitome sizes rather than scaling the images. Of class you'll want to include that style sheet within an IE conditional comment so that other browsers won't meet information technology.

The Real Problem of User Context

Mayhap the almost fundamental problem with this approach is a problem with responsive images in general. Nosotros're using screen width and pixel density to decide user context, just information technology's not clear that such an arroyo is e'er advisable. Consider, for example, a notebook user accessing the Web via a smartphone'southward Wi-Fi hotspot.

Accessing the Web via a smartphone's Wi-Fi hotspot.

That user's Web browser will show all the characteristics of a high-density, wide-screen device, and a responsive website will delivery large, high-resolution images. Anything less will look poor on our user'south display, just these images may accept a long time to load over a wireless network. They could significantly increase the website's load time, and they may ultimately cost our user real money on their wireless neb. Given the choice, they might prefer lower resolution imagery.

Information technology turns out that this problem is a really hard i to solve. Smart people in the Web community are definitely discussing it, but so far at that place has been little consensus on an practical solution. For now, CSS-based context discovery is the best technique available.

Acknowledgements

A special thanks to Grady Kuhnline for kickoff describing how to way images that can scale proportionally. Also, the contfont.internet website that this article uses every bit an instance is available for reference on github.

Smashing Editorial (cp)

How Do You Get A Background Image To Center Across All Media Break Points,

Source: https://www.smashingmagazine.com/2013/07/simple-responsive-images-with-css-background-images/

Posted by: rosenbergequed1960.blogspot.com

0 Response to "How Do You Get A Background Image To Center Across All Media Break Points"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel