Author Archive

Coding Q&A: CSS Performance, Debugging, Naming Conventions


  

Howdy folks! Welcome to another round of Smashing Magazine CSS Q&A — the final one, as of now. One more time, we’ll answer the best questions which you sent us about CSS.

It was a great experience to run this Q&A with you — thanks a lot for sharing all your questions with us! We hope we answered them at the best possible, and we’ll surely be back with new and exciting Q&A rounds in the future. Enjoy Chris’ last round on CSS performance, best practices on CSS class naming, and more!

CSS Performance

Vitaly asks:

“Could you recommend some rules of thumb or general tips on how to improve the performance of CSS? What are your general thoughts on the performance issues of CSS? Would you recommend the tips from Jon Rohan’s talk?”

Most of the time, I don’t think you should even bother thinking about the performance of your CSS. However, you should absolutely be thinking about the overall performance of your website.

The first thing to check is your website’s response time. You’ll see that is the very first thing in the “Network� tab of Chrome’s Developer Tools. If that’s, say, a second or more, that’s pretty slow, and you should work to get that down. That means server-side caching, faster servers, more efficient servers or more servers.


CodePen rocks a respectable 216 millisecond response time.

Usually, that’s not the problem with slow websites. That’s the 20% in the 80/20 rule. The other 80% is front-end-related stuff.

In the vast majority of situations, doing any of the following things would take less effort and have a far greater impact on performance than CSS optimizations:

  • Remove one resource (JavaScript file, CSS file or image) from the page (i.e. concatenate them).
  • Ensure that the resources are compressed and Gzip’ed.
  • Ensure that your assets have expires headers that are set far out.
  • Host assets on a content delivery network (CDN).

You can learn more about these things in this slide deck that I’ve put together.

If you’re already doing all of these things and you’re still having problems, that’s where Jon Rohan’s tips can help. Simpler HTML and simpler CSS selectors can make a difference in page-rendering speed.

I just wouldn’t expect huge gains on an “average� website. Remember that for the GitHub “dif� pages in question here, the developers were able to remove thousands and thousands of elements and simplify kinda nasty selectors (such as tag-qualified classes) to achieve their 37% increase in rendering speed. Most of us aren’t in that position.

Naming Classes

Christoph Rumpel asks:

“I would love to hear your opinion and some best practices on CSS class naming. Do you use BEM styles, or do you have your own convention? I am now looking for the best way to keep my CSS code simple, performant and reusable. Please let me know your thoughts on that topic and especially on how you would name nested containers and on what to consider when using selectors.”

I’ve just heard the saying, “There are only two hard things in computer science: cache invalidation and naming things.� Apparently it’s a quote by Phil Karlton that has been turned into an adage. By “naming things� is meant that moment when it’s up to you to choose a name for something. Any name would technically work, but a poorly chosen name will cause confusion and likely haunt your project moving forward. A good name will make for more understandable code and make things easier for all.

HTML class names (yes, we’re supposed to call them HTML classes, not CSS classes) are absolutely one of those things with which naming is important. It’s commonly taught that a class name like leftSidebar or bigRed is bad because it describes the desired look (which could change), rather than the content it contains (which is less likely to).

For myself, I just do my best to describe the content it contains. The best scenario is one in which I’ve identified a pattern and then named that pattern. Then I choose the most semantic element possible to go with the content and roll with it. For instance, a row of icons with numbers beside them might become class="stats". Here are a couple of classes from my currently open project:

<section class="pen-grid group">

<div class="single-pen">

<header class="collection-header">

<img class="user-avatar">

<span class="views">

These have served me well so far. I can understand what these elements are from either the HTML or the CSS.

Regarding wrappers, if a wrapper is needed solely for design reasons, I’ll often use a div (which has no semantic meaning) and apply -wrap to whatever other class name makes sense, so that I know it’s purely for design. No shame in that, if you ask me.

Debugging Preprocessed CSS

Andrea Verlicchi asks:

“I’ve read you’re a great fan of Sass/SCSS, like me. But most colleagues don’t use it because they are concerned about debugging the page, meaning they can’t just inspect the page and easily get the line of CSS where the rules are declared. How would you answer that concern?”

The way this pans out in my life is this: it doesn’t matter. My CSS structure is so organized and I know my text editor well enough that I can quickly jump to the CSS that I need without the help of line numbers in the developer tools.

However, I can understand that not all situations are like this. Seeing line numbers might be especially helpful when working with less familiar code or with code that you haven’t written. You’ll be happy to know that Sass supports source maps, and recent versions of Chrome support source maps, so you’ll be matching up line numbers in no time. If you use Compass, add this to your config.rb file:

sass_options = { :debug_info => true }

Now you’ll get proper line-number mapping:

source-maps-on

If you’re still on Firebug, then FireSass is essentially the same.

Staying Up To Date

Rouzbeh Sarrafieh asks:

“How does a novice/intermediate developer such as myself, who only does HTML and CSS and uses jQuery plugins, not get overwhelmed with all of the new things constantly being popularized and used so widely these days? From Gzip’ing and minifying CSS to using GitHub, CodePen and Sass and optimizing for all of the new resolutions and screen sizes with media queries, while implementing best practice techniques that seem to be changing at such a rapid pace — it all seems like so much to learn without having the time when you have a full-time job.”

It certainly can be overwhelming. The bad news is that being in Web design and development has gotten more complicated over time, and it’s not showing any signs of getting any simpler. The good news is that you don’t need to know every little thing in order to be a good Web worker, and many of the most important skills are timeless.

Are you good at understanding problems and figuring out solutions? Then you’ll be useful forever. Are you good at holding your customers’ hands, figuratively speaking, and making them feel comfortable through the creation of their website? Then you’ll be useful forever. Do you have good taste? Then you’ll be useful forever.

The rest you can figure out bit by bit, as you need it. I feel like my generic advice of “Just build websites� is relevant here. If you’ve read a bit about preprocessors and want to give them a try, then take a day and try it out on the next website you build. The same goes for anything you feel is newfangled or that you feel behind on. You don’t have to do it all at once.

For an overview of just some of the tools in my workflow, here’s a talk you can watch. The slides for that, as well as another one specifically about staying up to date on Web technology, are available here.

When To @extend

Ross Lavery asks:

“Could you provide some insight on when you prefer using Sass @extend (requiring a “semanticâ€� class of some sort to be added to the markup so that it can have @extend added to its style definition) versus simply adding a “non-semanticâ€� class to the markup numerous times. I’ve been struggling with which direction to go in, and Harry Roberts seems to prefer avoiding @extend for the most part, because it means coming up with a “semanticâ€� name for something that would have otherwise just required a class in the first place. I’ve had the same thought myself — having to just make up a silly name for a container for the sake of then extending a placeholder in Sass. Feels a bit backwards really.”

I wouldn’t pigeonhole @extend as being just a way to have semantic class names by extending non-semantic ones. Certainly it can be used that way, and, honestly, I have no big problem with that. I would think of it more generically, like: “Gosh I wish this class had the same stuff as this other class.� There are any number of reasons why that could be useful.

For instance, say you have this pattern on your website of a user avatar, user name and user location. It has some layout variations depending on how it is being used and on which page. You could have a class name like class="user-meta" for the most common variation, and then add classes to it (e.g. class="user-meta user-meta-small"), where the second class would override things set in the first class in order to get what you need. But that setting and overriding process is tedious and fragile compared to just setting what you want to begin with. Instead, you could have your .user-meta-small @extend a base class for all user-meta variations, and set what it needs on top of the base. The result is more efficient CSS (no setting and resetting) and more efficient HTML (one class instead of two).

Talking about this stuff so generically is difficult, though, and can lead to silly philosophical arguments. If you don’t like this, don’t do it. Naming is such a personal thing that as long as you have a system and aren’t often fighting yourself, you’re probably doing fine.

(al)


© Chris Coyier for Smashing Magazine, 2013.


Coding Q&A With Chris Coyier: SVG Fallback, Vertical Rhythm, CSS Project Structure


  

Howdy, folks! Welcome to more Smashing Magazine CSS Q&A. It works like this: you send in questions you have about CSS, and at least once a month we’ll pick out the best questions and answer them so that everyone can benefit from the exchange. Your question could be about a very specific problem you’re having, or it could even be a question about a philosophical approach. We’ll take all kinds.

If you’re interested in exploring more Q&A, there’s a bunch more in my author archive.

CSS Project Structure

Stephen Beiler asks:

“Could you please explain your strategy for building CSS? How do you start and what does the structure of your style sheet look like? Do you use something like tip/comment helpers (e.g. the color style guide) or perhaps the related markup, or anything else? How do you structure your code?”

These days I’m using Sass for all my projects. Sass provides things that I’m sure you are all aware of — like variables and mixins, but it also provides a very simple and vital feature: includes. Just like you might use an include() function in PHP, or render a partial in Rails, you can @import another Sass file in Sass. Unlike the native CSS @import, which simply makes a request for that file, Sass goes and gets that file and includes the file’s content when compiling down to CSS.

I use this feature heavily while organizing and structuring CSS for a project. It allows me to break my styling into whatever files make sense for me, as the author. It allows me an ASCII drawing:

Ascii

On my recent redesign of CSS-Tricks, I ended up with 28 .scss files, most of which were modular bits only ever @imported into bigger style sheets. This worked really well for me, matching how I naturally organize things, and not an organization scheme forced upon me, nor one built from artificial hacks (like enormous files with commented separators).

Regarding the color style guide, one of those .scss files is always one I call _bits.scss, which is were I put all my re-usable “bits” that any of my other .scss files might need. Color variables, my own custom @mixins, etc. I’m a fan of setting up colors as variables right away in a project, so that you can reference them easily whenever needed. If you need variations on that color, you can use Sass functions like darken() and lighten() to adjust.

Slightly controversially, I like naming my colors based on their color, like $red, $blue, and $green, because then it takes me zero seconds to remember and actually use them. Whereas in the past, when I’ve tried to be super semantic about my colors and name them $brand, $secondaryHighlight, and $moduleBackground or things like that, I could never remember my own cleverness, and it slowed me down.

When To Use OOCSS

Michael Winczewski asks:

“Chris, what do you think of OOCSS? Do you use it in your code, and if so, how? When would you advise against using it? And when would you advise using it?”

I think it’s fantastic. It’s more of a way of thinking than a strict set of rules. I doubt that I understand OOCSS in the same way that Nicole Sullivan does, or that I understand SMACSS in the same way Jonathan Snook does. But I think I understand the spirit behind these movements and use them in ways that make sense to me.

What it boils down to for me is usually: write super semantic markup, but use a class name on just about every important “chunk”. Then style things largely based on those class names. It’s about identifying patterns and styling that pattern in a smart way. That way, this pattern can be re-used easily, efficiency is inherent, and no semantics are harmed. And this doesn’t mean going nuts with class names, it means using just the right amount.

Specifically to your question, I think these concepts work for every project. There isn’t anything I can think of that would warrant not doing it this way. It’s just a grown up way to approach CSS.

Selecting All Link Pseudo Classes

Ren Walker asks:

Is there a quick trick in either LESS, Sass, or with the tried and true CSS where you can select all the pseudo classes of an element? For example, instead of writing:

a, a:visited, a:active { }

You could conceivably do:

a:* { }

Sure. If you’re using Sass, you could craft your own @mixin to your needs. For instance:

@mixin all-link-psuedos($col) {
  &:link     { color: darken($col, 10%); }
  &:visisted { color: darken($col, 20%); }
  &:hover    { color: darken($col, 30%); }
  &:active   { color: darken($col, 40%); }
}

$linkColor: red;
a {
  color: $linkColor;
  @include all-link-psuedos($linkColor);
}

There is a selector combiner type of thing in just CSS as well.

:-webkit-any(a:link, a:visited, a:hover, a:active) {
  color: red; 
}
:-moz-any(a:link, a:visited, a:hover, a:active) {
  color: red; 
}

But this isn’t really the intended use case for it, since you could just comma separate those selectors just as easily. Plus, the browser support isn’t great. Double plus, chances are you want different styling for those things instead of the same.

Fallbacks For SVG

Angelo D’Ambrosio asks:

“What’s the simplest and most efficient way to let the browser choose whether to load the SVG or the bitmap version of an img or a CSS background, according to browser support?”

  1. Download a version of Modernizr that is trimmed down to just testing SVG (assuming that’s the only test you need).
  2. Run the test. If it passes, put in the SVG. If it fails, put in the bitmap.

Essentially:

if (!Modernizr.svg) {
  $("#logo").css("background-image", "url(fallback.png)");
}

Modernizr isn’t needed on every website in the world — it’s needed on websites where you need to very specifically fork style or behavior for browsers that do or don’t support a feature. For instance, if you have a geolocation feature on your website (but the feature works just fine by typing in an address manually), you may not need Modernizr to tell you about the lack of support, since you may not need to do anything anyway.

SVG is a perfect use case for Modernizr, because there is no simple native way to provide a fallback.

Modernizr
Modernizr gives you the clean fork you need.

Just for the record: the only reason you would need a fallback for SVG these days if you have to support IE 8 and down, or older Android.

Maintaining Vertical Rhythm

David Casey asks:

“Chris, what’s your strategy for maintaining vertical rhythm for typography / design elements in responsive design?”

Looking at a page of pure typography — where someone has set up a background of lines where you can see the vertical rhythm matching up perfectly — is pretty cool. You can get a sense for why that makes for nice reading (with the lines removed of course):

Baseline Grid

But I think it’s a bit of a fool’s errand to enforce perfection on it up and down every page of a website. One image inside the content will most likely throw the whole thing out of whack. Yeah, we could crop it, but do we want to be making choices like that for the design de jour? We could resize it, but then perhaps it’s not lining up to our vertical grid lines like we want. In a world of flexible media, I don’t think it’s worth it.

If you do think it’s worth it, do note Dan Eden’s Baseline.js which does image resizing to combat the baseline grid issue. Molten leading may also be of interest.

Does it matter if the rhythm gets off? I don’t think so. Well set text will still look good. Remember: the type will still be in rhythm with the text right around it. So who cares if it’s off with text thousands of pixels away from it, and perhaps off screen? Making sure the type looks good in general is far more important than adhering to an invisible grid dogmatically.

Responsive + Retina Background-Image

Smarajit Dasgupta asks:

“How to tackle CSS background images for both responsive and retina display. If we use a background-size of 100% to make sure the image resizes on smaller devices, how do we set the same background-size in media query (-min-device-pixel-ratio: 1.5) to half of the @2x image?

Also, to tackle images this way, should we set initial scale to one in meta viewport that we normally would for responsive websites? Would that be a problem as far as retina displays are concerned?”

This is a difficult question to answer because so much depends on the particular implementation and what your goals are. Presumably, your goals are:

  1. Make it look good all the time.
  2. Don’t waste bandwidth.

I can share with you how this works on a particular area of CSS-Tricks, in which I use a background-image that is both responsive (in that it works in a flexible width area) and retina (looks sharp on retina displays). The area is called The Lodge, and I used a snowy cabin graphic for the background.

The Lodge

That’s actually the “medium” breakpoint (I call it the “mama bear”) that many tablets see. There is a wider and narrower breakpoint as well. Like you, I want this website to look great on retina displays, but also worry about its bandwidth. Serving a background image that is big enough to look great on retina at the largest breakpoint to a non-retina display at the smallest breakpoint is not good.

What I do is put all the background-images in media queries.

/* Reverso Baby Bear */
@media (min-width: 320px) {
  .lodge-wrap {
     background: url(lodge-bg-small.jpg);
  }
}

/* Reverso Mama Bear */
@media (min-width: 800px) {
  .lodge-wrap {
     background: url(lodge-bg-medium.jpg);
  }
}

/* Reverso Papa Bear */
@media (min-width: 1400px) {
  .lodge-wrap {
     background: url(lodge-bg-large.jpg);
  }
}

Doing it this way means that only one of those will match and only one resource will be downloaded. There is also is no “default” (outside a media query) which runs the risk of starting to download before being overridden.

I also make each of those three different images larger than they need to be, and let them scale down with background-size: 100%;. That way they are retina ready all the time, whether or not the device is. A bit of a waste sometimes, but at least I’m smart enough not to supply the largest image all the time.

If you want to get extra fancy, you’d need two media queries for each breakpoint: one for retina and one for non-retina. In my case, I’d have six total media queries… they’d be pretty complex, but it’s do-able. Here’s the two for the smallest breakpoint:

@media only screen and (min-width: 320px) {

  /* Small screen, non-retina */

}

@media
only screen and (-webkit-min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (   min--moz-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (     -o-min-device-pixel-ratio: 2/1)    and (min-width: 320px),
only screen and (        min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (                min-resolution: 192dpi) and (min-width: 320px),
only screen and (                min-resolution: 2dppx)  and (min-width: 320px) { 

  /* Small screen, retina, stuff to override above media query */

}

You’d repeat that for the next size breakpoint(s), overriding the background as you go down. Here’s more code and some more information on that.


© Chris Coyier for Smashing Magazine, 2012.


Coding Q&A With Chris Coyier: SVG Fallback, Vertical Rhythm, CSS Project Structure


  

Howdy, folks! Welcome to more Smashing Magazine CSS Q&A. It works like this: you send in questions you have about CSS, and at least once a month we’ll pick out the best questions and answer them so that everyone can benefit from the exchange. Your question could be about a very specific problem you’re having, or it could even be a question about a philosophical approach. We’ll take all kinds.

If you’re interested in exploring more Q&A, there’s a bunch more in my author archive.

CSS Project Structure

Stephen Beiler asks:

“Could you please explain your strategy for building CSS? How do you start and what does the structure of your style sheet look like? Do you use something like tip/comment helpers (e.g. the color style guide) or perhaps the related markup, or anything else? How do you structure your code?”

These days I’m using Sass for all my projects. Sass provides things that I’m sure you are all aware of — like variables and mixins, but it also provides a very simple and vital feature: includes. Just like you might use an include() function in PHP, or render a partial in Rails, you can @import another Sass file in Sass. Unlike the native CSS @import, which simply makes a request for that file, Sass goes and gets that file and includes the file’s content when compiling down to CSS.

I use this feature heavily while organizing and structuring CSS for a project. It allows me to break my styling into whatever files make sense for me, as the author. It allows me an ASCII drawing:

Ascii

On my recent redesign of CSS-Tricks, I ended up with 28 .scss files, most of which were modular bits only ever @imported into bigger style sheets. This worked really well for me, matching how I naturally organize things, and not an organization scheme forced upon me, nor one built from artificial hacks (like enormous files with commented separators).

Regarding the color style guide, one of those .scss files is always one I call _bits.scss, which is were I put all my re-usable “bits” that any of my other .scss files might need. Color variables, my own custom @mixins, etc. I’m a fan of setting up colors as variables right away in a project, so that you can reference them easily whenever needed. If you need variations on that color, you can use Sass functions like darken() and lighten() to adjust.

Slightly controversially, I like naming my colors based on their color, like $red, $blue, and $green, because then it takes me zero seconds to remember and actually use them. Whereas in the past, when I’ve tried to be super semantic about my colors and name them $brand, $secondaryHighlight, and $moduleBackground or things like that, I could never remember my own cleverness, and it slowed me down.

When To Use OOCSS

Michael Winczewski asks:

“Chris, what do you think of OOCSS? Do you use it in your code, and if so, how? When would you advise against using it? And when would you advise using it?”

I think it’s fantastic. It’s more of a way of thinking than a strict set of rules. I doubt that I understand OOCSS in the same way that Nicole Sullivan does, or that I understand SMACSS in the same way Jonathan Snook does. But I think I understand the spirit behind these movements and use them in ways that make sense to me.

What it boils down to for me is usually: write super semantic markup, but use a class name on just about every important “chunk”. Then style things largely based on those class names. It’s about identifying patterns and styling that pattern in a smart way. That way, this pattern can be re-used easily, efficiency is inherent, and no semantics are harmed. And this doesn’t mean going nuts with class names, it means using just the right amount.

Specifically to your question, I think these concepts work for every project. There isn’t anything I can think of that would warrant not doing it this way. It’s just a grown up way to approach CSS.

Selecting All Link Pseudo Classes

Ren Walker asks:

Is there a quick trick in either LESS, Sass, or with the tried and true CSS where you can select all the pseudo classes of an element? For example, instead of writing:

a, a:visited, a:active { }

You could conceivably do:

a:* { }

Sure. If you’re using Sass, you could craft your own @mixin to your needs. For instance:

@mixin all-link-psuedos($col) {
  &:link     { color: darken($col, 10%); }
  &:visisted { color: darken($col, 20%); }
  &:hover    { color: darken($col, 30%); }
  &:active   { color: darken($col, 40%); }
}

$linkColor: red;
a {
  color: $linkColor;
  @include all-link-psuedos($linkColor);
}

There is a selector combiner type of thing in just CSS as well.

:-webkit-any(a:link, a:visited, a:hover, a:active) {
  color: red; 
}
:-moz-any(a:link, a:visited, a:hover, a:active) {
  color: red; 
}

But this isn’t really the intended use case for it, since you could just comma separate those selectors just as easily. Plus, the browser support isn’t great. Double plus, chances are you want different styling for those things instead of the same.

Fallbacks For SVG

Angelo D’Ambrosio asks:

“What’s the simplest and most efficient way to let the browser choose whether to load the SVG or the bitmap version of an img or a CSS background, according to browser support?”

  1. Download a version of Modernizr that is trimmed down to just testing SVG (assuming that’s the only test you need).
  2. Run the test. If it passes, put in the SVG. If it fails, put in the bitmap.

Essentially:

if (!Modernizr.svg) {
  $("#logo").css("background-image", "url(fallback.png)");
}

Modernizr isn’t needed on every website in the world — it’s needed on websites where you need to very specifically fork style or behavior for browsers that do or don’t support a feature. For instance, if you have a geolocation feature on your website (but the feature works just fine by typing in an address manually), you may not need Modernizr to tell you about the lack of support, since you may not need to do anything anyway.

SVG is a perfect use case for Modernizr, because there is no simple native way to provide a fallback.

Modernizr
Modernizr gives you the clean fork you need.

Just for the record: the only reason you would need a fallback for SVG these days if you have to support IE 8 and down, or older Android.

Maintaining Vertical Rhythm

David Casey asks:

“Chris, what’s your strategy for maintaining vertical rhythm for typography / design elements in responsive design?”

Looking at a page of pure typography — where someone has set up a background of lines where you can see the vertical rhythm matching up perfectly — is pretty cool. You can get a sense for why that makes for nice reading (with the lines removed of course):

Baseline Grid

But I think it’s a bit of a fool’s errand to enforce perfection on it up and down every page of a website. One image inside the content will most likely throw the whole thing out of whack. Yeah, we could crop it, but do we want to be making choices like that for the design de jour? We could resize it, but then perhaps it’s not lining up to our vertical grid lines like we want. In a world of flexible media, I don’t think it’s worth it.

If you do think it’s worth it, do note Dan Eden’s Baseline.js which does image resizing to combat the baseline grid issue. Molten leading may also be of interest.

Does it matter if the rhythm gets off? I don’t think so. Well set text will still look good. Remember: the type will still be in rhythm with the text right around it. So who cares if it’s off with text thousands of pixels away from it, and perhaps off screen? Making sure the type looks good in general is far more important than adhering to an invisible grid dogmatically.

Responsive + Retina Background-Image

Smarajit Dasgupta asks:

“How to tackle CSS background images for both responsive and retina display. If we use a background-size of 100% to make sure the image resizes on smaller devices, how do we set the same background-size in media query (-min-device-pixel-ratio: 1.5) to half of the @2x image?

Also, to tackle images this way, should we set initial scale to one in meta viewport that we normally would for responsive websites? Would that be a problem as far as retina displays are concerned?”

This is a difficult question to answer because so much depends on the particular implementation and what your goals are. Presumably, your goals are:

  1. Make it look good all the time.
  2. Don’t waste bandwidth.

I can share with you how this works on a particular area of CSS-Tricks, in which I use a background-image that is both responsive (in that it works in a flexible width area) and retina (looks sharp on retina displays). The area is called The Lodge, and I used a snowy cabin graphic for the background.

The Lodge

That’s actually the “medium” breakpoint (I call it the “mama bear”) that many tablets see. There is a wider and narrower breakpoint as well. Like you, I want this website to look great on retina displays, but also worry about its bandwidth. Serving a background image that is big enough to look great on retina at the largest breakpoint to a non-retina display at the smallest breakpoint is not good.

What I do is put all the background-images in media queries.

/* Reverso Baby Bear */
@media (min-width: 320px) {
  .lodge-wrap {
     background: url(lodge-bg-small.jpg);
  }
}

/* Reverso Mama Bear */
@media (min-width: 800px) {
  .lodge-wrap {
     background: url(lodge-bg-medium.jpg);
  }
}

/* Reverso Papa Bear */
@media (min-width: 1400px) {
  .lodge-wrap {
     background: url(lodge-bg-large.jpg);
  }
}

Doing it this way means that only one of those will match and only one resource will be downloaded. There is also is no “default” (outside a media query) which runs the risk of starting to download before being overridden.

I also make each of those three different images larger than they need to be, and let them scale down with background-size: 100%;. That way they are retina ready all the time, whether or not the device is. A bit of a waste sometimes, but at least I’m smart enough not to supply the largest image all the time.

If you want to get extra fancy, you’d need two media queries for each breakpoint: one for retina and one for non-retina. In my case, I’d have six total media queries… they’d be pretty complex, but it’s do-able. Here’s the two for the smallest breakpoint:

@media only screen and (min-width: 320px) {

  /* Small screen, non-retina */

}

@media
only screen and (-webkit-min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (   min--moz-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (     -o-min-device-pixel-ratio: 2/1)    and (min-width: 320px),
only screen and (        min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (                min-resolution: 192dpi) and (min-width: 320px),
only screen and (                min-resolution: 2dppx)  and (min-width: 320px) { 

  /* Small screen, retina, stuff to override above media query */

}

You’d repeat that for the next size breakpoint(s), overriding the background as you go down. Here’s more code and some more information on that.


© Chris Coyier for Smashing Magazine, 2012.


Coding Q&A With Chris Coyier: Responsive Sprites And Media Query Efficiency


  

Howdy, folks! Welcome to more Smashing Magazine CSS Q&A. It works like this: you send in questions you have about CSS, and at least once a month we’ll pick out the best questions and answer them so that everyone can benefit from the exchange. Your question could be about a very specific problem you’re having, or it could even be a question about a philosophical approach. We’ll take all kinds.

If you’re interested in exploring more Q&A, there’s a bunch more in my author archive.

Resolution Aware Sprites

Joshua Bullock asks:

Your last round of questions was titled “Box-Sizing And CSS Sprites” which offered some great answers for two separate items, but didn’t take them that one step further for responsive design. Ultimately, my question is this: Is there a preferred/suggested way of handling responsive sprites at all for multiple resolutions and image scaling? Is this even possible?

This is a hot topic lately because of the rise in “retina” displays. But really, this problem has been building up for a while. Us Web designers often work in “pixels”, for instance, setting the width of an image: img { width: 100px; }. But what is 100px? It’s been a long time since that literally referenced a pixel on the screen. These days it’s a rather arbitrary measurement. 100px ends up being around an inch on a physical screen, regardless of its resolution.

Retina displays made a really quick and big jump in resolution. Apple’s 27″ Thunderbolt Cinema display has 109 PPI (pixels per inch) while the 15″ Retina MacBook has 220 PPI (literally twice as dense) meaning there are more pixels on the drastically smaller screen.

If you are drawing a solid red box on the screen, no problem at all! The higher resolution display will simply draw it with more pixels. But what about a little icon that you designed at 16×16 “pixels” in Photoshop? Both a high-resolution display and low-resolution display need to display that icon at the same physical size, but the high-resolution display needs to essentially fake a lot of those pixels. It’s like when you enlarge a photo in Photoshop, it immediately starts looking like crap.

One solution is to make all your original images bigger. Instead of a 16×16 “pixel” image, you can actually make it 32×32 in Photoshop but have CSS size it to 16×16. Then the information is there for the high-resolution display.

Your question was explicitly about sprites. How can we make a sprite image that is twice the size for retina screens without making it a huge pain in the butt? Fortunately, Maykel Loomans recently published a very simple and clever technique for this.

Essentially, you make the sprite exactly (and literally) twice as big, while maintaining its proportions. Then in your “normal” CSS, you load up the “normal” sprite and do all the background-position and sizing stuff to make your sprite work. Then using media queries, you overwrite the background-image with your new retina sprite (when the conditions are correct). You use background-size to shrink the retina sprite, so you don’t have to touch the tedious positioning/sizing stuff. Yay!

span.rss-icon {
   background: url(sprite-1x.png)  72px 181px;
   width: 16px;
   height: 16px;
}

@media only screen and (-webkit-min-device-pixel-ratio: 2), 
       only screen and (min-device-pixel-ratio: 2) {
  span.rss-icon {
    background-image: url(sprite-2x.png);
    background-size: 50%;
  }
}

Liquid — Fixed — Liquid

Niels Matthijs asks:

The layout I’m trying to create is L1F2L3, meaning the first and third column are both liquid, while the center column is fixed. I’ve been trying some stuff out, and even though I came close a couple of times, the solution never really pleased me. Do you have anything on this?

The Flexbox method in CSS can hook you up with this solution, and it’s pretty easy:

<div class="grid">
  <div class="col fluid">
    ...
  </div>
  <div class="col fixed">
    ...
  </div>
  <div class="col fluid">
    ...
  </div>
</div>
.grid {
  display: -webkit-flex;
  display: flex;
}
.col {
  padding: 30px;
}
.fluid {
  flex: 1;
}
.fixed {
  width: 400px;
}

Flexbox

See demo. I’m hesitant to recommend this as a “real world” solution because the spec for flexbox has changed rather dramatically recently. The code above is the newer syntax which is supported only by Chrome 21+ at the time of this writing (see support charts). There is an older syntax (see demo) that has wider browser support, but will probably someday stop working.

If you are in a position where you know that the middle column will be the longest, you could have the parent container have percentage padding on the right and left sides and absolutely position the left and right columns within it (at the width of that percentage). And if you don’t know that, you could always measure the three columns with JavaScript, and set the parent container’s height to the tallest of the three.

The New

Peter Karlstein asks:

What are the most useful CSS tips, techniques, tricks that you’ve learned recently? Can you present a couple of your recent “Aha!” moments with CSS?

Messing around with the latest flexbox stuff (as I did above) was pretty fun, although not really useful quite yet.

In the past few months I’ve moved entirely to using Compass, which has been tremendously useful. Over time I’ve grown tired of the repetitive and finicky things in CSS. But Sass and Compass make authoring CSS fun again for me.

As far as little CSS “tricks”, I’ve had to use this one several times lately. Essentially, if somehow some super long string of text gets into a container with no spaces, it will break out of the container in a super awkward overlapping fashion. This is most common with user-generated content and users pasting in URL’s. I like applying this class to any user-generated text containers:

.prevent-text-breakouts {
  -ms-word-break: break-all;
      word-break: break-all;
      word-break: break-word;
  -webkit-hyphens: auto;
     -moz-hyphens: auto;
          hyphens: auto;
}

Before:

After:

Also, Uncle Dave’s Ol’ Padded Box is a good one to have in your toolbox.

Relative Font Sizing

Greg Nelson asks:

Do you think there will one day (hopefuly soon) be a way to set a font-size to be in direct relationship to the width of it’s parent element, or some other truly responsive measure? e.g. <p> font size could be a percentage of the width of a sidebar div it sits inside of, so that as screen width’s change (and width of sidebar changes, if it’s also a percentage of <body> width), the size of the font will change too?

Yep, that’s coming! You’ll be able to set font-size with vw and vh units. Those stand for “viewport width” and “viewport height”. 1vw = 1% of the current browser window’s width. Here’s the CSS spec for that. And here’s a tutorial on using them. This is how it will work:

At the time of writing this, there is only support in Chrome 20+ and IE 10. If you need full browser support now (and don’t mind using a bit of JavaScript), you can use FitText.js (best for headers only).

Media Query Efficiency

Mark Roland asks:

When organizing media queries in a CSS file, is there any advantage or disadvantage to how they are grouped?

For instance, is there a browser performance difference between using several media query blocks (e.g. “@media screen and (max-width: 480px) { }” ) so that element styles are defined together (header, nav, footer, etc.) versus placing all of the element styles for the specific media query into one single media query block?

The former allows for easier development, but costs increased file size. Are there browser rendering costs for redundant media queries?

Technically, probably yes. The worst offense is the extra file-size that it causes. Using one is clearly less text than using multiple. But the fact is if you gzip/deflate content (you probably are), that will eat that repetitive code for breakfast and it won’t even increase file-size too much. As far as CSS parsing time, that stuff happens so fast that you really don’t need to think about it.

So on a practical level: don’t worry about it. If you have some time to spend on making your website faster, losslessly optimizing your images will make a way bigger difference.

If anyone is confused on why Mark is asking this, it’s most likely because of the abilility that Sass and LESS have to “nest” media queries (see). This is a really neat feature that makes working with media queries a lot more clean an intuitive, as you the author. However, the final output results in many duplicated media queries. I know that addressing this issue is on the mind of the lead developer from Sass.

Onward!

Keep up the great questions, folks! Got a good one? Send it in, and we’ll be picking the best ones for the next edition.

Image source of picture on front page.


© Chris Coyier for Smashing Magazine, 2012.


Coding Q&A With Chris Coyier: Code Smell And Type On A Grid


  

Howdy, folks! Welcome to the new incarnation of Smashing Magazine’s Q&A. It’s going to work like this: you send in questions you have about CSS, and at least once a month we’ll pick out the best questions and answer them so that everyone can benefit from the exchange. Your question could be about a very specific problem you’re having, or it could be a question about a philosophical approach. We’ll take all kinds.

We’ve done a bit of this kind of exchange before with a wider scope, so if you enjoy reading the Q&A, check out my author archive for more of them.

Designing For Email

Andrejs Abrickis asks:

“Sometimes I face trouble with HTML email design and the proper CSS code. It takes quite a lot of time to make it cross-client compatible. I would like to know your opinion about the best CSS reset that could help to speed up email newsletter development. Is there any good tool for testing HTML emails?”

First and foremost, I recommend keeping emails very simple. Ask yourself what the primary message of the email is and how well the current design of the email is serving that. Could it simply be text? Would it be better if it was text? I find that’s often true.

If you are certain you need to make an HTML email, I’d again error on the very simple. An idea I’ve been toying around with is making the email design the size of a portrait smartphone layout. That constraight forces you to think about the message again, enforces simplicity (and as a side bonus, will look good on both mobile and desktop clients). When is the last time you got an email and thought: “Man, I wish this email was more complicated!”

HTML Email Boilerplate
HTML Email Boilerplate provides a template of sorts, absent of design or layout, that will help you avoid some of the major rendering problems with the most common email clients out there — Gmail, Outlook, Yahoo Mail, etc.

But you wanted to know about cross-client compatibility and testing. Do check out the HTML Email Boilerplate. It was created in the same spirit as the HTML5 Boilerplate in that it addresses all the various quirks across email clients and gives an example of a very minimal structure by which to start. I’ve tried to use it as is, but I have to admit that I found it a bit too much for the simple email work I was doing. More complex and varied emails will certainly benefit from it and it’s also certainly a great reference for snagging quick problem-solving bits of code.

The two simple rules of thumb for HTML email development are:

  1. Use tables for layout. This is still the most sturdy layout method for cross-client.
  2. Inline style everything. Any other CSS support is spotty.

Designing using inline styles is a big pain in the butt, so I’d recommend developing with a <style> block in the <head> for your CSS. Save that as your development copy, and then just before deployment, run it through MailChimp’s Automatic CSS Inliner Tool which will do the dirty work of inline styling everything for you.

Speaking of MailChimp, you might want to consider just using their service to build and deploy emails. Their templates are already cross-client compatible (plus they have a testing service). Their designer tool is easy to use and helps you through the process. Not to mention, you get all these other huge benefits like better deliverability that you can’t get on your own, statistics, support, and many more features. Sorry if that sounded like an ad, but I’m all about using services that make our lives easier and better as developers.

MailChimp isn’t the only service on the block either, Campaign Monitor is also great, and do great things for the developer community, including maintaining this epic chart of CSS support for email clients.

Campaign Monitor HTML Email Reference
CSS support on Campaign Monitor.

Type On A Grid

Maxime Parmentier asks:

“I was wondering how you keep a consistent line-height in every element of your page? It’s much more difficult than it sounds in practice. Any tools or techniques that you can recommend?”

Often times that practice is called maintaining a “baseline grid.” Here’s a demo from a Richard Rutter article. And another demo from a Wilson Miner article. I’ve played with it myself a bit.

Dave Rupert offers a talk about responsive design, where he discusses how ems are useful for baseline grids because they are based on ratios. He also talks about how they are particularly good in the math-ridden world of responsive design. Here’s an example by Dave of type lining up nicely to a grid that also accommodates some of the weirdness of different-sized headers.

Baseline Grid
View this example.

There is a book by Khoi Vinh all about grids (including type grids) called Ordering Disorder: Grid Principals for Web Design. Khoi teaches all about grids but is clear that you don’t have to be dogmatic about them. Breaking the grid sometimes is OK, as long as you come back to it. I think one nice metaphor he mentions is about syncopation in music—the rhythm is broken on purpose during a song, so that when it kicks back in, it’s noticed and feels good.

Centering And Resets

Smarajit Dasgupta asks:

1. What is a decent browser-compatible way to center floated (or inline) elements like buttons and links in flexible (or unknown) width scenarios?

2. What is your preferred CSS reset in the HTML5 age? Do you still advise the usage of the great Eric Meyer’s reset, which pretty much strips all the browser-induced styles for elements? Or do you use something such as normalize.css or write your own on a case basis?”

1. Inline elements are easy to center, as they respect the text-align value of the parent, which you can set to center. So say you have a bunch of anchor links in a row, you’d just wrap them in a nav element and apply the center text alignment to that (like this). If you need them to behave a bit more like block level elements (e.g. be of a set width or height), you can make them display: inline-block; and they will still stay centered (like this).

Unfortunately you can’t center a floated element. I’m not surprised really, as the “what happens if” scenarios surrounding that are too many to count. But just for funzies, let’s say you had two columns of text and you wanted to “center float” an image between them, meaning that the text in the left column would wrap to the left, and the text in the right column would wrap to the right. You can “fake” this by positioning two elements half the size (might as well be pseudo elements, because they have no semantic meaning) on the right-side of the left column and left-side of the right column. A picture is easier to understand:

Floating Image
The floating kitty demo.

Then you would place the element in the space that makes sense (probably with absolute positioning). More about this idea here.

2. I like normalize.css. I don’t like the idea of stripping things away just to put them back. So my process is to take a copy of normalize.css, not remove anything, but change some declarations to my liking (which still ensures consistency, because you are being explicit). Then include that in my global style sheet like I would include a reset, and go from there.

Opacity Blues

Chris Klein asks:

“How do I stop inheritation of opacity? I can’t use another png with 50% opacity and higher z-index above it as the layout has to stay 100% liquid. Also, I tried to insert spans between the box with opacity and the following boxes—but the opacity still is inherited to all other boxes it follows. Even if the following boxes claim opacity: 1;, it doesn’t matter, inheritation goes on.”

There are a lot of little bits in there that make me wish we could look at the exact layout you’re working with. If the backgrounds in question are flat colors, just use RGBa or HSLa. These are both color value types you can use to declare an alpha value, which essentially means “what percentage transparent is this color?”. For instance rgba(255, 0, 0, 0.5) means “50% red”. This makes a lot more sense than using actual opacity on element, which as you know, affects everything inside (not just the background).

As you also know, opacity affects all child elements and you can’t fight against it by setting a child element’s opacity higher (the child does have full opacity by default, it’s just within a parent that doesn’t). It is like that for good reason. We would be much worse off if, in order to fade out an area of a website, we had to select theoretically infinite child elements and fade each individually.

If the background in your design isn’t a flat color, you can join the club for wishing there was a background-opacity property. One thing you may want to try are pseudo elements. Leave the main element at full opacity, but apply ::before and ::after selectors that you position as needed and apply opacity to those. Nicolas Gallagher has a demo of that.

Pseudo Element
The Jupiter oppacity demo.

Border-Radius On Images

Donovan Hutchinson asks:

“Why isn’t it possible to directly apply border-radius to an image? And is the best approach to use a wrapping div?”

It is possible! You apply it just like you think you would:

img {
  border-radius: 10px;
}

Border Radius
Border Radius demo.

I think there was some confusion on this for a while, because in the not-so-distant past, Firefox 3.6 required the use of -moz-border-radius for rounded corners, and that implementation didn’t work on images. IE9 was the first version to support border radius and it does so un-prefixed and perfectly fine on images so even IE isn’t a concern here.

If you absolutely need Firefox 3.6 (and down) support (1.55% global usage and falling fast), yep, like you mentioned, you can get it by using a div instead and setting the background-image of the div to the src of the image. You would do that in your template wherever it spits out that URL (or if that’s not possible, with a bit of jQuery):

$("div.avatar").each(function() {
  var el = $(this);
  var url = el.find("img").hide().attr("src");
  el.css("background-image", "url(" + url + ")");
});

Spotting Bad Code

Michael Zanzini asks:

“How can you tell if your CSS code smells? What are the signs that the code is sub-optional, or that the developer hasn’t done a good job? What do you look for in the code to determine how good or bad it is?”

The most obvious way to tell: does the website look all screwed up? Then it’s bad CSS. If the website looks perfect, then it passes the first test.

The next thing I’d look for without getting too down and dirty is the formatting. I wouldn’t care about trivial things like tabs or spaces or spacing after selectors, but instead general cleanliness and consistency. Does it look like they have a style that they adhere to, or is it sloppy and random? Clean code is a sign of a respectful developer. It’s not proof the code is good but it’s a good start. Mind you, you should be looking at the authored CSS, not deployed CSS, as that could be altered during a build process.

After those rather obvious things, you’ll have to get mentally more into the code. Read through it. Do the selectors look nice and rational (e.g. nothing too ridiculously specific like .article #comments ul > li > a.button)? Does there appear to be an awful lot of repeated code (e.g. the same complex box-shadow declared 15 times)? Is it absolutely enormous (e.g. 100k would be be absolutely enormous, as a check)?

The last thing I might do is try and test understandability by running a personal test. Assuming that you are half-way decent at CSS yourself, think of a small task you might need to do on the website. Adjust the colors and spacing of a particular header. Try and do it. Was it easy? Good. Was it hard to figure out? Not good.

Submit Your Question!

Keep up the great questions, folks! Got a good one? Submit your CSS question via our form, and we’ll pick the best for the next edition. So long!

(jvb)


© Chris Coyier for Smashing Magazine, 2012.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress