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

Advertisement

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 talk1?”

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 Server
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 rule2. 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 deck3 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 tips4 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 to5 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 maps6, 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 FireSass7 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 websites8” 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 watch9. The slides for that, as well as another one specifically about staying up to date on Web technology, are available here10.

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 prefer11 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)

↑ Back to topShare on Twitter

I create websites and help others create better websites through writing and speaking. I consider myself a lucky man for getting to work in such a fun and rewarding field.

  1. 1

    That’s pretty cool about the line numbers for SASS. That’s one of the primary reasons I’ve never tried it out. A lot of the time I end up working with other peoples old code and being able to get the exact line number from Firefox saves me so much time. I didn’t want to lose that ability even if I do organize my CSS better than they did, I’ve grown used to it.

    0
  2. 2

    Better adage:

    There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

    0
  3. 3

    Yea, this is some really good points. I think one of the most important things is when you start with a basic format of naming convention, to definitely continue with it. I think when people change their coding styles/names all the time throughout a site is when a dev like me gets fairly annoyed. When I first started using SASS and LESS, I wasn’t to particular about the way people always wanted to group elements, and then when you have nesting madness going on sometimes and it can get really confusing, but you learn how to find classes quicker the more you use it when debugging. But our team uses LESS and it has grown on me when used correctly even though I guess that’s completely subjective to many devs.

    What I like to do when creating a project from the ground up is to obvious split your css files up in layout.css, module.css, overrides.css (which contains the module/layout overrides), type.css , etc. And then combine them with a build script we have. And when a class is extended in the body tag or wrapper tag I know that means there will be a layout override, (ex: body class=”home two-col”) and when i view the css I know immediate I set all my overrides like .home.two-col (forgive my naming convention). So when a class is usually combined it wont be concatenated in the css, therefore utilizing a more object oriented method through out my site. I do the same thing with modules, if i have a module override the classes will be concatenated but if i had the css all loaded on one file i would know fairly quickly whats happening by not even looking at the site. This is just my way which is just a combination of a lot of ways I have learned over the years, but depending on the site I have a different ways of splitting up the styles.

    Sometimes I don’t even use a base.css because I have base styles in layout, and base styles also in modules and typography so for me I feel like its confusing to have it in one file since I want to give someone else looking at my css to know more about architecture of the sites styles. Then again (me being a hypocrite…mkay), for smaller sites, I do use a base.css which contains all the type and modular styles and then another stylesheet for overrides. Also when I use LESS i have a variable.less file that can change font size relative to the entire site, and even particular overrides that makes it easier for other devs to go in and adjust sizes or color. I do agree with what you say on using @extends and it does make you think. I was just curious as to how you split up your styles and what naming conventions you use when naming the actual style sheets as well?

    0
  4. 4

    Please Clarify: in the 1st slide deck in this post by Chris there are a few slides at the end of the presentation that imply jQuery is bad-or maybe I am just confused. jQuery being bad is news to me. Is there a better alternative than jQuery that is way faster.

    0
    • 5

      It’s a library and libraries contain alot of information that you don’t need for your current project. However right after he explains that jquery is the smallest and widest spread library and it almost has no impact on performance. If you are a die-hard javascript-coder you might be able to save a few kb/miliseconds by not using jquery…

      0
      • 6

        I think that as soon as you use quite a bit of the functionality it is perfectly fine to include jQuery. But when you use it only for one or two very simple things it sometimes might be better to just use regular JavaScript for that.

        0
  5. 7

    I enjoyed this post as well as the slides. I’m not a fan of Sass or Less but worth it a try. ^_^

    Thanks Chris.

    0
    • 8

      If sass/less seems like much at the beginning just start out small. It will have a huge impact on your workflow.

      Start with several sass files so your ‘main’ css is empty. So normalize css styles etc go into other sass files. This way you don’t have to scroll to start coding in your css. Then add some basic things like color you would like to re-use. (e.g. color: #ff0000 will be color: $red)

      My sass setup usually is something like:
      _boilerplate.scss
      _normalize.scss
      _body.scss (this is where I code css)
      _mediaqueries (depends on project)
      main.scss (here you can define standard colors and fonts)

      includes and mixins can come later, but starting out with this will help you develop much faster (in my case)

      0
  6. 10

    I’ve always been in love with your work Chris Coyier since I started work in CSS… :-)

    0
  7. 11

    That’s interesting to read about this 20/80 rule. I’ve not heard of that before. Annoyingly my own site seems to be the other way around and the response time is close to 80% sometimes. I guess you’ve convinced me that I need to move to another host :)

    0
  8. 12

    Very nice article, even if you’re lazy at reading long online articles, you dont wanna miss the slides, great way to get input, especially if its combined with humor!

    KILL IT WITH FIRE!

    0
  9. 13

    Very helpful article, thumbs up Chris! From all your screencasts and talks I knew pretty much everything but I like when things are packed together, quick and easy to digest.

    I started using @extend recently for my clearfix ( Nicolas Gallagher’s Micro Clearfix ). Instead of a mixin it does not create so much extra code and so far I fell that is the way to go. Not sure if it can be consideren best practise, though. Any tips for a better way to include clearfixes?

    0
  10. 14

    Thanks for the wonderful list to make myself updated

    0
  11. 15

    “Remove one resource (JavaScript file, CSS file or image) from the page (i.e. concatenate them).”

    I often see that but the truth is more complicated. Please don’t just use one big css and one big .js : it’s slower than having a few of them (4 to 6 total, depending on various factors).
    Also, the server response time DOES matter. If your page is quite complex to generate, you can obtain impressive results by flushing the head part containing links to css and script tags with external src as soon as possible.

    0
    • 16

      Hi Joey, you said:

      “Please don’t just use one big css and one big .js : it’s slower than having a few of them (4 to 6 total, depending on various factors).”

      That’s not really correct. If you have the exact same lines of code, spread over 4-6 files, compared to a single file, the 4-6 files will make your page load slower than the one file — simply because because it’s loading multiple files. HTTP requests are usually the first thing listed in page speed tools, because that’s one of the primary causes of slow pages.

      Also, if you’re worried about the maintenance headache of multiple files, well, generally you should be concatenating the files in production, not in development. Of course, this requires some kind of deployment solution, so sometimes that means more work or else more understanding of how to do those sorts of things more easily.

      0
    • 17

      I agree with Louis here – saving HTTP requests really does have a performance improvement.

      If you still want to keep separate files for development/code management, then consider running a service like minify http://code.google.com/p/minify/

      It collates, minifies, gzips and caches file bundles into one request, and can have a real performance boost.

      I’d also recommend serving generic libraries (jQuery etc) from a CDN like Google https://developers.google.com/speed/libraries/devguide#Libraries – if your visitors have been to another site that uses libraries served this way, then it’s already cached for your site. If they haven’t, then requesting assets from a different domain doesn’t prevent other assets loading at the same time (maximum simultaneous requests etc still apply, but that’s another topic)

      0
  12. 18

    Thanks Chris. Really helpful stuff here. Especially like what you said about the softer skills that make a designer/developer last in this crazy web world and continue producing quality work. That’s encouraging to hear and something that’s good for all of us to remember. Referring to this part in particular:

    “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.”

    0
  13. 19

    Thanks for the tips. I always minifty my stylesheets and javascript files to keep the file sizes down.

    I use http://dean.edwards.name/packer/ for javascript

    and http://tools.w3clubs.com/cssmin/ for CSS

    0
  14. 20

    Thanks so much for answering these important questions! Will definitely look into these resources.

    0
  15. 21

    Great post, thanks!

    0
  16. 22

    I really enjoyed reading this post. And the slides were just as equally useful. Thanks.

    0
  17. 23

    Hey guys, I wrote some CSS naming conventions months ago:
    https://github.com/redaxmedia/ncss

    The goal of NCSS is to provide additional information just by reading unknown CSS.

    - What elements, tags and sections are affected
    - What is the relation of one CSS class to another
    - Where to add related CSS declarations

    Regards
    Henry

    0
  18. 24

    Chris, I believe there is an error in your slide can’t find http://html5-weekly.com, but http://html5weekly.com/ looks same.

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top