Maintainable CodeUsing White Space For Readability In HTML And CSS

Advertisement

Right up front, I’ll offer some simple advice: In production, your code should be as performance-friendly as possible. This means, Gzip’ing, concatenating and minifying as many assets as possible, thus serving the smallest possible files and the least number of files. I don’t think anyone would argue that these suggestions aren’t best practices (even if we don’t implement them in every project).

labyrinth-comic
Well-written, readable code doesn’t create mind games and labyrinths when other developers read it. (Image: Toca Boca)

Now that we’ve got that out of the way, how can we use white space in development code to ensure that our files are as readable and maintainable as possible? Well, we could consider a number of options, starting with some basics.

Basic HTML Indentation

I think most if not all of us add basic indentation in our HTML:

<header>

  <hgroup>
    <h1>Section title</h1>
    <h2>Tagline</h2>
  </hgroup>

  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about/">About</a></li>
      <li><a href="/services/">Services</a></li>
      <li><a href="/contact/">Contact</a></li>
    </ul>
  </nav>

</header>

<div class="main">
  <p>Content goes here.</p>
</div>

The principle here is that whenever something is nested, you indent, so that it’s clear where everything is in the markup’s hierarchy. With simple HTML nesting, the content in the <head> section is often neglected, but keeping the nesting consistent here, too, is good practice.

For example, the following sample code is fairly readable, even with no nesting:

<!DOCTYPE html>
<html>
<head>
<title>Foo</title>
</head>
<body>
<!-- content… -->
</body>
</html>

However, with much more content in the <head> section, nesting could make it easier to scan the contents:

<!doctype html>
<html class="no-js" lang="en">
  <head>
    <meta charset="utf-8">
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <title>HTML5 Please - Use the new and shiny responsibly</title>
    <meta name="description" content="Look up HTML5, CSS3, etc features, know if they are ready for use, and if so find out how you should use them - with polyfills, fallbacks or as they are.">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

    <link href="http://fonts.googleapis.com/css?family=Francois+One|Open+Sans:400italic,400,800" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <script src="js/libs/modernizr-2.0.min.js"></script>
    <script>if (location.host == 'h5bp.github.com') location.href = '//html5please.us/'</script>

  </head>
  <body id="gfs">
    <!-- content… -->
  </body>
</html>

This last chunk of code is taken from the HTML5 Please website. As you can see, when the content in the <head> section starts to get larger, indenting makes things a bit easier to digest at a glance. Notice that the <head> and <body> elements are indented, because they are both immediate children of the <html> element.

Of course, some developers might have a slightly different method of indenting in certain areas, but the idea is basically the same; the intention is to make the code easier to read in a development environment.

Basic CSS Indentation

In addition to indenting HTML, many developers (me included) will do matching indentation in any corresponding CSS. The following code would match the HTML shown in the first example above:

header {
    color: blue;
}

    hgroup {
        color: green;
    }

        hgroup h1 {
            line-height: 1.5;
        }

        hgroup h2 {
            font-size: 15px;
        }

    nav {
        background: purple;
    }

        nav ul {
            float: left;
        }

            nav ul li {
                font-size: 20px;
            }

                nav ul li a, nav ul li a:visited {
                    text-decoration: none;
                }

.main {
    border: solid 1px #ccc;
}

To some, this seems a bit obsessive. But I prefer it because it helps me to scan the CSS and find matching hierarchies without having to read each selector. Of course, this type of hierarchy in your CSS should be used sparingly if you’re implementing modular CSS principles that encourage class-based modules and limited use of the descendant selector (for example, ul li).

Certainly, some of the code above is kind of awful; I wouldn’t recommend tying your heading and list styles to a specific context like that. But for the purpose of understanding this concept of indenting CSS, look at it as a theoretical example.

The point is that you have the option to indent CSS to match the HTML’s structure, thus making it easier to scan and easier to make sense of relative to the markup.

Of course, as is the case with a few things mentioned in this post, some of this doesn’t apply when you’re using a CSS preprocessor. For example, the nested selectors option for Sass would make this last tip quite different in such an environment.

Readable CSS3

Let’s take our abuse of white space even further. Many new CSS3 features allow for either comma-separated or space-separated value sets. Two simple examples are multiple backgrounds and transforms. Let’s see how we can make these easier to read:

.example {
    background: url(images/example.png) center center no-repeat,
                url(images/example-2.png) top left repeat,
                url(images/example-3.png) top right no-repeat;
}

.example-2 {
    transform: scale(.8)
               skew(20deg, 30deg)
               translateZ(0);
}

Notice what we’ve done here? Instead of keeping the entire value on a single line (which can get lengthy in some cases — especially when gradients and vendor prefixes are involved), we’ve put each value set on a new line, aligned with the one above it.

Thus, each of the three backgrounds is on its own line, and each transform function is on its own line, left-aligned with the first of each example.

Generally, this might go against the idea of having a single property per line (assuming, of course, that you’re not doing single-line rule sets). But when compared to the alternative of potentially really long lines, this is a good option, and it makes these rule sets very easy to read.

Dealing With Vendor Prefixes

As mentioned, if you’re preprocessing your CSS or using -prefix-free, then this advice doesn’t apply. But you could manipulate white space to make your vendor prefixes easier to read at a glance:

.example {
    -webkit-transform: scale(.8);
       -moz-transform: scale(.8);
         -o-transform: scale(.8);
            transform: scale(.8);
}

Here we’ve lined up the colons so that the values align, making it easy to scan all values to ensure they’re the same. I can’t tell you how many times I’ve adjusted only the WebKit value in a rule set like this and forgotten to do the rest. Of course, this illustrates the importance of preprocessing, but if you’re not doing that yet, then this use of white space is a good option to consider.

Additionally, many text editors offer a feature called “block edit” or multiline editing. This is available in Sublime Text, Vim, Coda and probably most others. Using this feature is that much easier when the values you’re changing are aligned vertically.

Readable File References

The gist of this next suggestion comes from a tweet by Twitter Bootstrap cofounder Jacob Thornton. The idea here is that if a list of file references is contained in your document, you can make them easier to read by doing something like the following:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
                <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
                               <link rel="shortcut icon" href="assets/ico/favicon.png">

The example above is taken directly from Bootstrap. Here, all href attributes of the <link> elements are aligned. This makes it easier to refer to or adjust a <link> tag because the update will usually be to the value of the href attribute.

Of course, this somewhat violates the rules of indenting HTML. So, alternatively, you could opt for this:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72"   href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed"                 href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon"                                href="assets/ico/favicon.png">

This latter example seems cleaner and has the bonus of aligning the other attributes, although that’s not as necessary in my opinion.

But wait. What if you don’t care that the href attribute is listed last (which seems to be the custom and is unnecessary for validation)? Then you could do this instead:

<link href="assets/ico/apple-touch-icon-144-precomposed.png" rel="apple-touch-icon-precomposed" sizes="144x144">
<link href="assets/ico/apple-touch-icon-114-precomposed.png" rel="apple-touch-icon-precomposed" sizes="114x114">
<link href="assets/ico/apple-touch-icon-72-precomposed.png" rel="apple-touch-icon-precomposed" sizes="72x72">
<link href="assets/ico/apple-touch-icon-57-precomposed.png" rel="apple-touch-icon-precomposed">
<link href="assets/ico/favicon.png" rel="shortcut icon">

No white space tricks needed here, because the href attributes align just fine. But if you’re bothered by the lack of alignment of the other attributes, or if you just can’t stand the thought of the href attribute being listed first, then you’ll have to opt for one of the preceding solutions.

Readable Conditional Classes

The concept behind the alignment of attributes is nothing new. HTML5 Boilerplate has been doing this sort of thing for some time now with its IE conditional classes. Here’s what that chunk of code looks like in the latest version:

<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

In this case, the class attribute on the opening <html> tag in each conditional (and, incidentally, the tag itself) is being aligned, because this is the part of the code that’s most relevant to readability and maintenance, and the part of the code that would suffer most in readability if this alignment were not present.

Readable Comma-Separated Selectors

Sticking with Boilerplate, let’s go back to CSS. Here’s something used in that project’s main style sheet:

html,
button,
input,
select,
textarea {
    color: #222;
}

Here, instead of keeping all of the comma-separated selectors on a single line — which would be more difficult to scan — each selector is put on a new line. This can be helpful when the selectors are somewhat lengthy, as in this next example, also taken from Boilerplate:

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

Similar to the idea behind aligning HTML attributes discussed above, this vertical alignment makes the code a breeze to scan through when compared to scanning a single seemingly never-ending line of comma-separated selectors.

Can Your Text Editor Help With Any Of This?

As a long-time developer who has grown accustomed to coding by hand, my knowledge of the features of different text editors is fairly limited.

Some text editors or IDEs might do some of this automatically. Also, plugin developers can use some of these patterns to create plugins or extensions that do this sort of thing automatically or at the click of a button.

If you have any suggestions of built-in tools or extensions to text editors that can assist with this, I’m sure Smashing Magazine’s readers would be glad to hear about them.

Conclusion

We’re all encouraged to do whatever we can to make code in a development environment as easy to read and maintain as possible. I hope these suggestions will improve your code in this way.

And knowing that this use of white space won’t bloat our files is comforting — after all, this is not for production code. So, do whatever you feel is necessary to make your HTML and CSS easier to deal with, and be sure to minify those assets when deploying to production.

Finally, if you have any suggestions on using white space in HTML or CSS, we’d be glad to hear them.

(al)

↑ Back to top

Louis Lazaris is a freelance web developer and author based in Toronto, Canada. He blogs about front-end code on Impressive Webs and curates Web Tools Weekly, a weekly newsletter for front-end developers.

  1. 1

    Great Article! But I think I found a little mistake: You set the semicolon wrong on the background-Example under “Readable CSS3″, just to prevent some confusion ;-)

    0
  2. 3

    What we need is better tools for layouting our files.

    With respect to the proposed suggestions in this article but I think I’d faint when presented with a css file layouted like above. Readability is very much dependent on the person viewing the file and tastes differ. Wildly. Even within a small team working in the same company, same room, adhering to standards can be tricky, let alone should we try to define a global standard.

    I hate property/line css, scannability for me is all about scanning selectors, not so much properties. Nesting css structures only decreases the readability of a file. For me. Looking at the code above it’s clear that for you it’s an entirely different experience.

    We really need an editor that figures these things out for us. Instead of doing all the work ourselves, just have a fine-grained set of layouting tools, so each person can code in his own style, while sharing his files with others who can then view it in their preferred way.

    0
  3. 4

    i agree that writing code should be readable if passed on to other devs but indenting css for me might not work as my css files get bigger and bigger, it might just add to the confusion rather than seperating and adding comments to each section(e.g. /* links */ , /* typography */, /* grid */ ),

    also, using haml / sass improves code readability, no need to worry about indentation and tracing where that pesky closing tag is. not to mention it can also save devs so much time

    0
  4. 5

    Nice reminder. many of us already know this but we don’t follow it :-)

    http://procssor.com/ is a nice tool for CSS formatting.

    0
  5. 6

    I think rampant use of indentation can be more of a hindrance than a help. This is especially true for large chunks of HTML that go beyond what can vertically fit on one screen (e.g., #main, #sidebar). Indentation in scanning HTML means the eye has to move HORIZONTALLY as well as vertically. This provides the same problem that long vertical lines of text encounter—losing what line you’re on, and what line is next. The amount of times I’ve had to scroll back up on code to see what level I’m on is frustrating.

    Instead of indentation, how about color-coding or or using a font’s weight to show blocks? Or the background color of the lines of code, increasingly dark as it gets deeper into the code? There has to be a more effective method than indentation—just because indentation has been around the longest doesn’t mean it’s the best option.

    0
    • 7

      Totally agree on overuse of indentation. Lots of editors seem to like to use tabs for indentation and then if you look at it in another editor, it’s way out of whack.

      As for colour-coding, a lot of the code editors do that already. Sublime Text 2 seems to be making the most waves in development circles.

      Your idea about the blocks being highlighted (low-lighted?) is interesting. It would be pretty cool to have an editor that would do that, but then bring that block to full brightness again when you’re in it editing. Personally, I’m rather against a lot of use of colour — backlighting blocks in a rainbow of colours would drive me nuts — but a pleasant gradation in a single hue might work well.

      0
    • 8

      Edward Unthank brings up some good points. It’s not always possible to use indentation for convenience and efficiency’s sake. I personally think the idea of color-coding could work in some instances, and possibly could make life a lot easier for the dev.

      0
  6. 9

    Nice article
    personally i depend on firebug or the developer tool in chrome, even in the stage of developing and maintaining

    0
  7. 10

    I usually don’t format my css like that

    0
  8. 11

    Great read! There are a few practices here I am going to try to integrate into my markup.

    I don’t like indenting CSS unless the rule is definitively a child of the previous rule. Looking at your example above I would not indent like that. Since CSS is cascading, you maybe have styles in your nav element that you reuse outside your header.

    I have a suggestion to add as well. Since I started using AngularJS this year the number of attributes I have in a tag have skyrocketed. To accommodate the messiness I started indenting and using a new line for any tags that have more than one attribute. Using your link example:

    <link
        rel="apple-touch-icon-precomposed"
        sizes="144x144"
        href="assets/ico/apple-touch-icon-144-precomposed.png">
    
    <link
        rel="apple-touch-icon-precomposed"
        sizes="114x114"
        href="assets/ico/apple-touch-icon-114-precomposed.png">

    These comments do not appear to accommodate formatting so I hope you get the picture.

    0
  9. 12

    The only thing I’d like to add: please realize that many (most?) developers are working on monitors that are very wide, yet not very tall. Thus, long lines make good use of the large available width, and therefore are much less of a problem than suggested in such readability articles.

    Likewise, suggesting vertical white space as a best practice (which you hinted at) actually goes against the screen real estate many work with, which is not tall at all.

    All in all I’m fairly neutral on which standard is best, I’m hoping tools solve these things because doing it manually and checking upon such rules generally is a royal waste of time.

    0
    • 13

      I agree with the wide monitors comment, however a few developers in our office now work with them rotated to portrait, which I think is a clever use of space when it comes to coding.

      0
    • 14

      But then you’re suffering from other readability problems. It’s very well noted that long lines are much harder to read.

      And in the specific case of CSS, the rules themselves are objectively easier to scan on multiple lines than on one line. If you’re looking for, say, ‘margin’, you can scan down the column and pick it out. If there are 10 lines that’s 10 “letter height” units. If you have to read across, it’s probably over 100 “letter width” units.

      While you and others commenting are correct that everyone has preferences, there are some styles that are objectively better than others. If you are working in a team you need to compromise on what is generally better for everyone.

      0
      • 15

        I made up my own system to make use of the horizontal screen estate as I also find it awfully annoying to have to scroll lines over lines for just single CSS attributes and leave 80% of my screen blank.
        I simply put the attributes in a specific hierarchical order in terms of their importance and effect on the display of the HTML element, e.g. a line could look like this:
        selector { display, float, position, width, height, margin, padding, border, font, background, color, other purely aesthetic attributes…
        -webkit-transition,
        -moz-transition,
        … }

        I add CSS3 on extra lines to make them more discernible and easier to maintain.
        If the lines are really too long, you can also break the first line into the display & positioning line and aesthetics line. I’m faring fairly well with this as I know where to look for specific attributes. But as I work alone, I don’t know how team-adaptable this is, nor have I worked with a CSS preprocessor before.

        0
    • 17

      While many have wide monitors (and this isn’t necessarily all *that* new) — many also place windows side-by-side, or use multi-view apps. The experience (personal, subjective) of reading lines as wide as my monitor is that I get very very lost.

      That said, lots of indentation also sucks for me, because I might be in an 80-char window and the lines of code go zooming off to the right again.

      Most of the folks I’m working with are very happy with a 2-space indent (no tabs!). In some languages where leading space is actually part of the syntax, it keeps things from zooming over.

      0
      • 18

        You’re mentioning no tabs for indentation twice now, so I’m wondering why you’re against using them?

        My preference goes to tabs instead of spaces. This way every dev can set their preference on how to interpret it: width of x spaces. Using two real spaces means you’re forcing your two spaces on other devs.
        (And also, if you’re writing CSS to go live without any pre/postprocessor, 1 tab is just 1 bit, while 2 spaces is 2 bits, 3 makes 3 etc. In large files these bits can count up. Of course one should always minify before going live, but hey, I’m making a point here!)

        0
        • 19

          I agree. I hate editing or pasting code that indented with spaces. I prefer 4-space width tabs. I know lots of people prefer 2, but when using tabs that’s just a matter of a setting in your editor. We can work on the same file and both enjoy our preferred spacing. Whereas changing from 2 actual spaces to tabs or more spaces is much more involved.

          Also, the fact that a tab is a single character helps not only with file size (which as you point out *shouldn’t* carry over to production,) but also with editing. Many/most editors will allow the tab key to add X number of spaces (and may even detect it automatically from the open document,) but a single backspace typically removes the indentation one space at a time.

          Basically, from my experience, the behavior of tabs is more consistent across editors, except that you’re usually able to change the width to suit your preferences. If you’re editing in notepad, sure, 8 spaces is ridiculous, but… don’t edit in notepad. :)

          0
    • 20

      Ferdy, I tend to agree. I use a standard desktop monitor and also a wide screen laptop in my work. For some of the more involved projects, I just can’t use the indentation, because it would actually slow down the whole process and cause some confusion. On the other hand, I do think that indentation could be great for HTML, but for CSS, I’m a bit iffy.

      0
  10. 21

    I have been writing this way for a while now and find that it not only more readable, but allows me to write more complicated less, while focusing on the structure of the selectors rather than the noise of the attributes.

    Here are 2 examples of my approach.
    http://cl.ly/N0XN
    http://cl.ly/N1dq

    0
  11. 22

    We actually structure our LESS (and CSS) a bit different. See here -> Link: http://sqzd.me/WUIOvB and one from another of my team members: http://cl.ly/N1pK

    This allows your brain to parse out the selectors by scanning down the page. Then you can follow it right to see the style. It makes it faster to see the relation ships with-in LESS. The first example is also great for wider screens like Ferdy said.

    0
  12. 23

    Re: The Article – For many set it and forget it type elements like and conditionals, I tend to just use CTRL+F because I am not likely to need to work in those parts of the document frequently. With CSS, I’m all for anything that improves readability because I minify it anyway, negating any whitespace issues.

    Re: the site – I hate to have to do this here, but the Smashing contact form appears to not be working. This comment is related to the article, but is actually a quirk of the CSS on this site, not related to the author.

    First note
    —-
    I have a quick CSS quirk that I encountered on your site. I’m not particularly OCD, but since I took the time to track it down, I thought I could take the time to share the quirk and it’s location.

    On http://coding.smashingmagazine.com/2013/02/19/using-white-space-for-readability-in-html-and-css/ I came to the section “READABLE CONDITIONAL CLASSES” and noticed that the declarations did not line up. I found that the padding for `pre, code {}` in main.min.css was offsetting only the first line of code blocks. I could suggest a fix, but I’m sure your staff is capable and would be better able to make sure that it did not break other considerations.

    While I’m writing, I noticed your “Chars left:” counter below does not update. At this point it still reads “420.”

    Great site. I wouldn’t bother to tell you if I wasn’t here all the time.

    Second note
    —–
    When submitting a form here with too many characters, it returns a 404 for http://www.smashingmagazine.com/contact-form-thank-you/.

    I thought it was related to the character count, but subsequent attempts with a few words seem to have failed as well

    /backtoyourregularlyscheduledcomments

    0
  13. 24

    Nice enough article, but way too long for the tiny snippets of real knowledge it put forth.

    I guess “white space” (and too much of same) is an issue on articles as well as CSS files :)

    It would have been better if there was less padding/white space and more real usable stuff like – how do COMPANIES (who may employ any of us reading) actually feel about /enforce formatting rules?
    More data on the tools available?

    oh, but that would probably require research and work :)
    At least we have Google!

    I’d give this post a solid C. Nothing much, but no egregious mistakes either

    Again it is often the comments that provide the value added, especially those from Matthijs, Ferdy and Vyas who introduced me
    to the excellent web tool, “http://procssor.com/”

    0
  14. 25

    Standards, yeah. Make your own personal standards, and stick with em ;)

    What you’ve written down here is basically nothing other than a coding style guide. A lot of it is what I’m using and suggesting to others as well. Some rules look more like “let’s beautify” instead of “let’s make it more readable” thou.
    Take the idea of the CSS 3 / custom browser CSS implementations as an example: Tab- or block-wise intendation is easily done, this one thou is not. And thus, is also not a real life example.

    Another note about the conditional comments scenario: I’d avoid playing around with intendation – this might look good on non-related browsers, but IE might fall into Quirks mode, which we’d like to avoid at all costs, wouldnt we? ;)

    cu, w0lf.

    0
  15. 26

    I can’t recommend the tool Recess enough for CSS prettification: https://github.com/twitter/recess

    0
  16. 27

    I’m a big fan of nesting CSS. It’s especially tidy when you keep all your attributes on a single line.

    0
  17. 28

    For the Coda 2 Users out there here are some helpful plugins I use:

    Coda PHP & Web Toolkit (Has HTML & CSS Lint/Cleaner):
    http://www.chipwreck.de/blog/software/coda-php/

    Also CSSComb is available as a plugin for many editors as well as an online version:
    http://csscomb.com/

    0
  18. 29

    Awesome article and it was good to see that folks of the web are trying new ways to write code as well. I use white space and comments in the head section and I like your idea of laying out the CSS code into hierarchies. The only areas that I personally would be staying away from are readable conditional classes and readable file references and this is purely on the basis that I have no issue locating these lines of code when maintaining websites. All in all, a good read! I’ve been waiting for something like this to come back to Smashing Magazine for ages!

    0
  19. 30

    Indenting CSS file like that is not necessary. If you group related sets of selectors, the nesting order of the corresponding markup is evident in the selectors themselves.

    0
  20. 31

    Great article, I love the idea of indenting and formatting CSS this way … nice.

    0
  21. 32

    Thanks Louis, very handy post. I do practice indentation in my code already but there are some really good tips you’ve given.

    0
  22. 33

    Is gzip’ing even a good idea when the target is smartphones and CPU-limited portable devices?

    0
  23. 34

    OK, I think white spaced can make html layout looks more clearly

    0
  24. 35

    Good article, and some thoughtful replies too.

    Generally if working with large documents I’ll use the Collapse Level feature in Notepad++. I’m sure it’s in other programs too. Essentially if you have a select dropdown with say 250 options (eg. countries) you just press Ctrl+Alt+F to collapse all of the options temporarily out of view.

    With regards to the article it’s got some nice ideas, some of which I already follow. If you wanted to improve readability further you could always alphabetize your CSS too. eg:

    html,
    button,
    input,
    select,
    textarea {
    font-size: 1em;
    color: #222;
    border: 1px solid #000;
    }

    It would be quicker to read as:-

    button,
    html,
    input,
    select,
    textarea {
    border: 1px solid #000;
    color: #222;
    font-size: 1em;
    }

    Should be fairly straight forward to automate this so it can be run on any stylesheet. Sorry for the formatting, it doesn’t say what code to use to format?

    0
  25. 36

    My CSS starts out as a heredoc section in a Perl script, which contains a bunch of
    rules of this general form:
    div#idHeader h1 {
    font-family: $header_font_list;
    font-size: 1.75em;
    line-height: 1.2em;
    margin: 16px auto 16px auto;
    }
    When I run the script, it resolves all the variables (which need only be defined once,
    so $bgcolor, $body_font_family, or any other definition can be changed throughout
    by editing one line), and it also strips unnecessary spaces, line feeds, and comments.
    It then writes the resulting CSS code to projectname.css, ready to upload to the server.

    0
  26. 37

    I have recently changed the way I layout my CSS from the “new line for each attribute” to one long line. As long as the monitor is pretty wide I find it much easier to identify each part when scrolling down. If each section of your css is labelled clearly i.e. /*– NAVIGATION–*/ etc I find it much easier to find what I’m looking for.

    I use the same approach on my html. Although I tend to use less commenting in my html.

    I like the look of the http://procssor.com/ though.

    0
  27. 38

    Another good refresher ;) Someone should come up with a “develop etiquette” site as we have a “http://photoshopetiquette.com/” already. Centralizing the best practices code-wise.

    0
  28. 39

    As developers, we can be very critical of anything outside of our preferred method. In truth, it doesn’t matter whether our code is nested or not; as long as the hierarchy of the selectors is comparable to the markup. It’s all about your preferred method and rendering clean code. I have used the nesting method for years; until recently. I may still employ a few nesting elements just out of habit; but I think for beginners this is great advice. Whether everyone agrees with your article or not, criticism isn’t needed here.

    0
  29. 40

    Sublime Text 2 is, in my opinion, the best text editor for programmers. NetTuts published an almost 4-hour video tutorial teaching how to make your Sublime workflow perfect.

    https://tutsplus.com/course/improve-workflow-in-sublime-text-2/

    0
  30. 41

    I always have my CSS on one line

    I only ever search for the selectors rather than “margin” etc.

    Everyone saying that it makes it harder to find specifics need to utilise apple+f a (or windows alternative) a little more, I find my selector then apple+f “margin” and boom I have my margin that I need to edit.

    I do use /*comments*/ a lot to separate my fonts/head/body etc to make life easier for any developers needing to access my stuff.

    0
  31. 42

    how about not to indent(format) everything and then use some indent online tool like
    http://www.freeformatter.com/html-formatter.html

    0
  32. 43

    I wasn’t happy with many of the HTML indentation packages available on Sublime Text 2, so I ported the script I created for TextMate. You can find it here:

    https://github.com/rareyman/HTMLBeautify

    Peace!

    0
  33. 45

    Pedro Sombreireiro

    March 5, 2013 5:29 am

    Writting CSS and HTML all indented and clutter free it’s really a best practice, but more often than not, we find yourself in projects where we need to go from a UX perspective to a working prototype in the shortest timeline possible. In these situations, i think each person will find their own style of writing code. Personally, i don’t indent my code as explained in the article. It would take me more time to do it and since i use LESS and in the end, the css file is minified … i just use the rules of coding LESS. But i love to see a pretty formatted CSS file and HTML file, i must say :) I just don’t have time to do it :)

    0
  34. 46

    I like having the closing bracket on the same line as the last declaration and also the Ruby whitespace conventions:

    http://screencast.com/t/kdgu4AFk

    0
  35. 47

    Good article. It has sparked even more insightful comments. Nice one.

    0
  36. 48

    Christian Varga

    May 1, 2013 3:15 am

    There are some great tips here, but it’s interesting that you mention minimal use of the descendent selector then use `nav ul li`. While this has been common practice for as long as I can remember, there’s actually no need for the `ul` part of the selector. 99% of the time an `li` is going to be nested under a `ul`, and if not, it would be under an `ol` which you’d probably want styled the same anyway. So using a selector like `nav ul li` is quite redundant, you’d be better off using `nav li`. The same goes for `nav ul li a`. If your nav just contains a simple `ul` (aka, without any other random anchors outside the ul that require different styling), then `nav a` would suffice.

    0
  37. 49

    you might wanna check out http://webdeconstructor.com/
    it’s an web-app that let’s you analyse what websites are made from by deconstructing their HTML structure in a matter of seconds

    0
  38. 50

    FWIW, when you program in Python you have to develop a good style for indenting. It’s required by the language. Once you’ve done a few basic Python programs and scripts, it becomes second nature.

    0
  39. 51

    I always have my CSS on one line

    I only ever search for the selectors rather than “margin” etc.

    Everyone saying that it makes it harder to find specifics need to utilise apple+f a (or windows alternative) a little more, I find my selector then apple+f “margin” and boom I have my margin that I need to edit. seen here http://www.mcconnellgroup.ca/blog

    I do use /*comments*/ a lot to separate my fonts/head/body etc to make life easier for any developers needing to access my stuff.

    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