HTML & CSS
Article

Using Helper Classes to DRY and Scale CSS

By Ahmad Ajmi

You are starting a new web project and looking for a new CSS methodology that will help you scale your code. A growing set of techniques for writing modular CSS are available, including SMACSS, BEM, and a number of other similar methodologies, all based on Object-oriented CSS (OCSS). As you can see, there are lots of techniques to write and organize CSS.

Besides all these methodologies, there is something that can help us write DRY, less repetitive code: Helper classes (also called utility classes).

This concept was discussed some time ago in Thierry Koblentz’s article on Smashing Magazine, but I thought I would explain the method in my own words here.

What Are Helper Classes?

Helper classes can help remove repetition by creating a set of abstract classes that can be used over and over on HTML elements. Each helper class is responsible for doing one job and doing it well. Doing this will make your code more reusable and scalable for many features that will be added in the future. So whenever you want to create a new component, you’ll just need to combine some classes together to build it.

Let’s see a simple example of what utility classes look like and how we can use them. Look at the following snippet of code:

.left        { float: left; }
.right       { float: right; }

.text-left   { text-align: left; }
.text-right  { text-align: right; }
.text-center { text-align: center; }

Here we’ve created a set of CSS rules that we can use later when building new components. For example if you want to align some content to the left you can use the text-left class. Likewise, you can use the left or right classes to float elements in the needed direction.

Let’s see another example of a box that needs to be on the left with its inner content centered.

We usually do something like this:

<div class="box">
</div>

With this CSS:

.box {
    float: left;
    text-align: center;
}

Instead, we can achieve the same thing using reusable and single-responsibility helper classes:

<div class="left text-center">
</div>

Notice how I removed the box class and instead added our predefined classes left and text-center.

If you want to change the float and align directions, instead of doing this on the non-reusable .box class, you can use other helper classes:

<div class="right text-right">
</div>

The grid system is a good example of helper classes in use. Here is an example from Foundation’s grid:

<div class="row">
    <div class="small-2 large-4 columns"></div>
    <div class="small-4 large-4 columns"></div>
    <div class="small-6 large-4 columns"></div>
</div>

Foundation provides numerous classes that can be used and combined together to create a grid system with different widths for different screen sizes. This flexibility helps developers create new customized layouts faster, without editing any CSS for the grid itself. For example:

  • .small-2 and .large-4 classes will set the width of an element based on the screen size.
  • The .row class sets the width of the container that holds the columns.
  • The .columns class sets the padding and floats.

Now that you understand what helper classes are, let’s take a look at some reusable classes we can add to our projects, presented below in different categories. Note also that the example will use some Sass variables, but naturally these are not necessary.

Margins and Padding

Margins and padding are probably the most used properties in our CSS. Adding some abstract classes that can handle this will DRY our code.

We start by defining a variable (using Sass) for the base space unit for our design. Let’s start with 1em and on top of that we can create classes for different space sizes.

$base-space-unit: 1em;

// Top margin
.margin-top-none    { margin-top: 0; }
.margin-top-quarter { margin-top: $base-space-unit / 4; }
.margin-top-half    { margin-top: $base-space-unit / 2; }
.margin-top-one     { margin-top: $base-space-unit; }
.margin-top-two     { margin-top: $base-space-unit * 2; }

// Top padding
.padding-top-none    { padding-top: 0; }
.padding-top-quarter { padding-top: $base-space-unit / 4; }
.padding-top-half    { padding-top: $base-space-unit / 2; }
.padding-top-one     { padding-top: $base-space-unit; }
.padding-top-two     { padding-top: $base-space-unit * 2; }

We can alternatively choose short class names, as in the example code below from Basscss

.m0  { margin:        0 }
.mt0 { margin-top:    0 }
.mr0 { margin-right:  0 }
.mb0 { margin-bottom: 0 }
.ml0 { margin-left:   0 }

Choose what works for you and your team. The long names will obviously make your HTML elements larger, but they are more readable in contrast to the short names, so you may need to look at your CSS to figure out how things work.

Width and Height

Imagine you want to set a section to be full height in different places on your website. The traditional way we did this was something like this:

<div class="contact-section">
    <!-- Content here... -->
</div>

And our CSS:

.contact-section { height: 100%; }

For other sections we would repeat the code:

<div class="services-section">
    <!-- Content here... -->
</div>

And the CSS:

.services-section { height: 100%; }

But we can reduce all of this with one class called full-height:

<div class="full-height">
    <!-- Content here... -->
</div>

Below are some similar examples, including the full-height class used above:

.fit         { max-width: 100%; }
.half-width  { width: 50% }
.full-width  { width: 100%; }
.full-height { height: 100%; }

Position and Z-index

Position-related properties can be combined with other properties like z-index to create a complex layout. We can create a set of classes to set the exact position of any element in relation to the viewport or an ancestor element (right, left, top left, etc):

.fixed    { position: fixed; }
.relative { position: relative; }
.absolute { position: absolute; }
.static   { position: static; }

.zindex-1 { z-index: 1; }
.zindex-2 { z-index: 2; }
.zindex-3 { z-index: 3; }

.pin-top-right {
    top: 0;
    right: 0;
}

.pin-bottom-right {
    bottom: 0;
    right: 0;
}

The “pin” helper classes are inspired by Mapbox’s CSS.

Let’s extend the full-height example to contain an element positioned at the bottom right.

<div class="full-height relative">
    <div class="absolute pin-bottom-right padding-one">
        Text to bottom right
    </div>
</div>

Demo

By combining more than one class, we can get the required result in less code. If you want to position the inner element at the top right, you can use the pin-top-right instead of pin-bottom-right. You might have noticed in the above code I also added another helper class: The padding-one class ensures the element isn’t flush against the edge of the container or viewport.

Floated Elements

Floating elements left or right can be done using left or right classes. The well-known clearfix class can be used on the parent element to clear floats, shown below using Sass’s parent selector:

.left  { float: left; }
.right { float: right; }

.clearfix {
    &:before,
    &:after {
        content: "";
        display: table;
    }

    &:after { clear: both; }
}

Demo

Aligning Elements

We can make text and other content align to any direction, using align-based helper classes:

.text-left    { text-align: left; }
.text-right   { text-align: right; }
.text-center  { text-align: center; }
.text-just    { text-align: justify; }

.align-top    { vertical-align: top; }
.align-bottom { vertical-align: bottom; }
.align-middle { vertical-align: middle; }

Visibility Classes

Visibility classes control the visibility of elements, depending on the screen size, device orientation, touch screen, or other factors. These can come in handy in responsive designs.

We could have the following classes inside of our media queries:

.hide-on-small { display: none; }
.show-in-large { display: block; }

And in our HTML:

<div class="hide-on-small show-in-large">
    <!-- content here... -->
</div>

The above element will be hidden on small screens but will be visible on larger screens.

We can also use these classes to control elements on touch devices:

.touch .show-for-touch { display: none; }
.touch .hide-for-touch { display: inherit; }

In the example above, the .touch class would come from the classes added to the <html> element by Modernizr.

A good example of visibility classes are the ones in Foundation and Bootstrap’s responsive-utilities.

Typography

In typography you can create classes for things like font weight and text manipulation, like ellipsis text.

.bold     { font-weight: bold; }
.regular  { font-weight: normal; }
.italic   { font-style: italic; }

.ell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.break-word { word-wrap: break-word; }
.no-wrap    { white-space: nowrap; }

Colors

Every application has different guides and brand rules which we can define in classes that essentially ‘skin’ our interface. This would include text color, backgrounds, and more.

Lets see how this can be translated to code. First let’s define our variables with Sass:

$white     :   #fff;
$gray      :   #2c3e50;
$dark-gray :   #95a5a6;
$dark      :   #2c3e50;

$notice    :   #3498db;
$success   :   #1abc9c;
$alert     :   #e74c3c;

Then we define our helper classes, based on the variables:

// Colors
.white            { color: $white; }
.gray             { color: $gray; }
.dark-gray        { color: $dark-gray; }

.notice           { color: $notice; }
.success          { color: $success; }
.alert            { color: $alert; }

// Backgrounds
.white-bg         { background-color: $white; }
.gray-bg          { background-color: $gray; }
.dark-gray-bg     { background-color: $darkgray; }

.notice-bg        { background-color: $notice; }
.success-bg       { background-color: $success; }
.alert-bg         { background-color: $alert; }

Two good examples of using color and background helper classes are found in the Mapbox and the Google Web Starter Kit projects.

Mapbox colors styleguide

Another use case is the notification component. Let’s see how we can style this with background helper classes.

<div class="white p1 mb1 notice-bg">Info</div>
<div class="white p1 mb1 success-bg">Success</div>
<div class="white p1 mb1 alert-bg">Alert</div>

Alerts

Lists

How many times have you wanted to get rid of the bullets and padding from the ul element? A class called list-bare, as used in inuitcss, can do that for you.

.list-bare {
    padding: 0;
    list-style: none;
}

Borders

Helper classes can be used to add borders to an element, whether for all sides or one side. So your CSS/Sass might look like this:

$border-color: #f2f2f2;

.border-all    { border:        1px solid $border-color; }
.border-top    { border-top:    1px solid $border-color; }
.border-bottom { border-bottom: 1px solid $border-color; }
.border-right  { border-right:  1px solid $border-color; }
.border-left   { border-left:   1px solid $border-color; }

Display Values

The following helper classes give us the ability to use the different values for CSS’s display property:

.inline       { display: inline; }
.block        { display: block; }
.inline-block { display: inline-block; }
.hide         { display: none; }
.flex         { display: flex; }

Conclusion

Following this principle of abstraction might be a much different approach from what you are accustomed to when authoring CSS. But based on my experience, and that of others I can say this is a very good approach to consider on your next project.

You can check out all the helper classes from this post in a new library I created called css-helpers.

You can learn from and explore the structure of the following projects:

Further Reading

  • Irony

    Or we could just use style attributes and forget about classes all-together!

    • http://ahmadajmi.com/ Ahmad Ajmi

      This is not the case at all, in the inline method we will only work with HTML and JUST UGLY HTML and don’t forget about specificity and other issues, But here we will manage HTML based on what’s on in the CSS side including our abstract basic rules (CSS helpers).

      • M S i N Lund

        And with this approach, what do we edit when we for example later want something (but not everything) previously floated left, floated right ?

        Do we edit the CSS or the HTML?

        This just moves the styling from the style-attribute to the class-attribute.

        Welcome to the 1990’s

        • LouisLazaris

          Why is that a problem, exactly? You’re telling us it’s a problem, just because it supposedly imitates something we did in the past? Besides the fact that it doesn’t, you haven’t explained anything practical other than the fact that somebody did this in the 90s, and therefore we shouldn’t do it.

          • M S i N Lund

            You cant possibly be this dense.

            Try reading the whole comment , not just the last line.

          • LouisLazaris

            You don’t ever edit those styles, that’s the point of the post. You have a library of classes that can be used anywhere.

            And what is it exactly that you’re going to change? Let’s look at an example:

            You use “float-left” on a bunch of elements. You no longer want one of those elements to be floated left. So, in your HTML, you change that one example to “float-right” or else remove the float class altogether.

            You also mention removing all instances of a particular class in the HTML, but how many would you really have that would matter? I think the only one that might matter are color-based ones, but even then, how many elements on the page have the same background color? Maybe 2? 3? If you’re creating static .html pages and not using some kind of back-end templating to assist with your HTML production, thus creating a maintenance inconvenience, then you’ve got bigger problems to deal with that are tantamount to putting a square peg in a round hole. So I can see why you’d have trouble.

            As I’ve already mentioned in a few other comments, nobody is saying this is the go-to method. It’s just one kind of modular CSS method. I see some problems with it too, but as I’ve mentioned, they’re the same problems that exist with any CSS architecture, and they have nothing to do with this “remove presentational styles” nonsense that people talk about that is not relevant to anything.

          • M S i N Lund

            You really don’t see how this is just the same thing as style attributes, with exactly the same problems?

            If you dont want style=”float:left” in your HTML,
            why on earth would you want class=”float-left” in it?

            Like you said, you just change that one example to style=”float:right” instead when you need.
            How many could there be …right?

          • LouisLazaris

            The difference is, the actual CSS is not littered in your HTML, instead it’s just one-purpose modules. That’s not CSS in the HTML, that’s just classes.

            I mean, think about it: If you add a class called “.box” that has 5 declarations in it in your stylesheet, how is that any different? Those 5 styles can still be viewed as the “box” presentation, taken as a single entity. It’s not as black and white as you’re implying. You just don’t seem to like bringing this down to a one-purpose selector thing.

            The other problem is that you’re not really providing an alternative that has greater benefit (at least not much greater).

            For example, what style of CSS do you prefer? Do you agree with a modular approach, just not overkill like this article discusses? If you do, then why do you want that modular approach? What benefit does it have? Is it not in order to DRY the CSS?

            Let’s say, again, you have a “.box” module with 5 or 6 styles attached to it. You use that class many times in your HTML. All of those boxes are floated left. So now you want to change a single box to not be floated left, but you want the rest to stay that way. What do you do? Well, you have one of two choices, create a whole new class to add to the one non-floated box, that has “float: none”, or else you duplicate the styles and repeat the whole chunk, so you can keep it out of your HTML.

            This is basically what I don’t understand about the arguments in this post. You’re saying it’s bad because the “presentation” is in the HTML, but no matter what CSS methodology you employ, you will always have some level of “presentation” in your styles.

            On the other hand, it is possible to have zero “presentation” in your markup. If you’re doing that, then you’re definitely doing it wrong, because then you’ll be stuck with awful selectors like “ul li div span” and “#whatever”, neither of which should ever be allowed in any stylesheet. These awful selectors will end up with boat loads of repeated font styles, colors, backgrounds, borders, and so on…. Not a DRY module in sight.

            So my point is that the customary alternative that pushes the “presentation doesn’t belong in CSS” view is only potentially marginally better than the stuff proposed in this article.

            Anyhow, I appreciate that you’ve taken the time to at least explain your position a little more. I see the challenges you now see, but I don’t see them as any more problematic than those found in an methodology or architecture. The fact is, CSS, in many respects, has always been broken and it’s almost impossible to avoid all the pitfalls.

          • M S i N Lund

            Good luck with that then.

          • Justin Mathew

            “You use “float-left” on a bunch of elements. You no longer want one of
            those elements to be floated left. So, in your HTML, you change that one
            example to “float-right” or else remove the float class altogether.”

            How is that any different then using an IDE to select all “float: left”‘s in a defined area and changing them, or better yet using SASS, to keep your semantics intact?

    • LouisLazaris

      Your “ironic” joke completely misses the point of the post and actually perpetuates the ridiculous myth that “presentational HTML” is somehow bad.

    • http://www.billyhalim.zz.mu Billy Halim

      When I am building a website, I only use style attributes for margin and padding, to create spacing between divs.

  • borisli

    While I completely agree with breaking down CSS into reusable, I am a bit worried about a complete loss of semantics in the code. It basically diminishes the benefit BEM brings to developers, which is increasing readability of the code, aswell as remove the need to edit markup, whenever styling changes.

    The question is – can this approach be applied while keeping BEM. I thought about using SASS’s @extend, but that would produces ugly selected whenever SASS is compiled. Im really open to suggestions here

    • http://ahmadajmi.com/ Ahmad Ajmi

      BEM and CSS Helpers are two way of thinking and the workflow is different (Component vs Atomic), but it doesn’t mean they can’t be combined together in the same project.

      I think in your case as your project already exist, you can make helpers like margins, padding and colors based on your project and gradually start to adapt them in some global elements that are not specific to BEM and in new features that you will add later.

      • http://kaliszczak.pl/ Janusz Kali Kaliszczak

        What about responsive when you need to change size/colour/alignment etc. and it’s no longer in sync with defined class names. Or two elements are left aligned on desktop and one is right aligned on mobile?
        This set of styling can and should be set one step earlier in preprocessor. e.g. @extend in SASS or mixins.

        • LouisLazaris

          That’s a good suggestion about the Sass, because then you could deal with some of the RWD problems that others are talking about. I think this method is quite compatible with Sass and other techniques, it would just take some time to get used to it and make sure to document things well.

  • Jens O. Meiert

    Anyone, don’t read this. Ahmad, I’m sorry, but whoever taught you, or wherever you learned, go elsewhere. This is all harmful advice and shouldn’t be spread. (Nothing personal, this post is just nonsense.)

    In a nutshell, for professional web development the exact opposites hold. Most notably:

    1) Use functional or generic ID, class, and custom element names [1]. That is so to achieve full separation of concerns (for better maintainability) and to get around unnecessary (and thus unnecessarily costly) HTML changes. The absolute same holds for helper classes.

    2) The HTML is critical to keep as minimal and clean as possible [2]. Generously using IDs and classes does the exact opposite, and in large websites and apps it becomes very costly, very quickly. (Let’s all remember that either ourselves or others need—and will!—touch all this code again.)

    I’m keeping this brief, however when it comes to DRYing up style sheets there are other things to look at. For example, be more thorough in your use of declarations [3], a thing that’s missed embarrassingly often. But nowhere, nowhere is there any case yet to all of a sudden use presentational HTML code again, and that in huge quantities. Please :)

    [1] http://meiert.com/en/blog/20080812/best-practice-ids-and-classes/
    [2] http://meiert.com/en/blog/20080926/get-the-html-right/
    [3] http://meiert.com/en/blog/20141009/css-dry-and-optimization/

  • http://www.tyssendesign.com.au John Faulds

    A lot of these classes also don’t make as much sense in a responsive context, e.g. you might only want to position:absolute elements on wider screens, not on mobile.

    • http://ahmadajmi.com/ Ahmad Ajmi

      You can add some specific classes inside a media query to be applied only for large screens.

    • LouisLazaris

      Why would that affect anything? You’re still going to have to write mobile styles with any other approach, so either way you’ll still have elements with pos:abs that don’t need it on smaller screens.

      I suppose it would help if someone who disagrees with this approach actually built a hypothetical example where this would cause problems, because I just don’t see it.

      • http://www.tyssendesign.com.au John Faulds

        Because adding a class of pin-top-right doesn’t make much sense when an element isn’t pinned top right in a mobile context.

        • LouisLazaris

          But that’s just semantics. In fact, I might argue that it does make sense that way, because at least that way you understand that the base styles for that component are “pinned top right”. I don’t think it’s as wrong as you’re implying. I don’t really understand why devs are so hung up on avoiding those types of names.

          Of course, you could just call it something generic like “box position” but now you’re back at square one, staring at your mobile styles, wondering what the base styles are supposed to be.

          It’s like anything. It has its pros and cons, but I don’t think the cons are as bad as people are claiming.

  • david2m

    The idea of CSS is to separate styling from the HTML/presentation. Doing what’s mentioned above is bringing styling back into the HTML. It’s nearly as bad as using the style attribute.

    • LouisLazaris

      No, the idea of CSS is not “to separate styling from the HTML/presentation”. What benefit is there rom thinking along those lines? None that I can see. Too many people have been pushing that view, but It has no real benefit. Besides, he’s not advocating putting CSS into the HTML here, he’s merely constructing a stylesheet that can be used to build components in the future without actually writing any CSS.

      Of course, I’m not saying this is the only approach one should use. I’m saying this technique has some decent pros to it and not really many cons other than the theoretical “mixing content with presentation”.

      • david2m

        So you’re saying you can’t see any real benefit to separating the presentation from the styling? My response to that is give web development. At the most basic level it’s separation of concerns.

        Using these “helper classes” is just an attempt to cover up and justify bad HTML/CSS planning and design. I’m seeing more and more of this littered all over HTML documents and it’s all thanks to articles like this spreading bad practices.

        Using lots of these classes does not make sense for responsive designs either. An elements style can change a lot from device to device. The HTML would not make sense when viewing it on different devices, again, that’s why the styling goes in the CSS and not scattered around the HTML.

        • http://ahmadajmi.com/ Ahmad Ajmi

          From it’s name they are called Helpers, they can help you authoring CSS, you don’t have to take it at all or leave it at all, it’s not the only way and it could be used with what ever you use to write your CSS. if it didn’t work in some cased like responsive as you said it might work in other cases and workflows. The web is changing and best practices also change over time.

        • LouisLazaris

          What is the practical value of “separation of presentation from styling”? What is the practical value of “separation of concerns”? What does that do for you that the technique above cannot do?

          Also, the argument about devices doesn’t really matter because, firstly, you wouldn’t be viewing source on a small device anyhow, and if you were, you’d be using developer tools, or else your original files, editing them for the purpose of updates. I can’t see any practical reason that “float-left” in the HTML of a mobile device (which nobody can see) would be detrimental in any way.

          In fact, as I pointed out in another comment, I would make the argument that it’s potentially beneficial. Because now, in your Media Queries, you can clearly see that the original styles are inherited from a module that floats the element to the left. I’d say that’s pretty helpful. After all, what’s the alternative? A class of “box”? How does that help you? How is that beneficial in a mobile environment, in which, again, nobody would even look at the HTML?

      • Nick Fitzsimons

        From the third sentence of the CSS 2.1 specification: “By separating the presentation style of documents from the content of documents, CSS 2.1 simplifies Web authoring and site maintenance.”

        The separation of styling from HTML (and, in theory though seldom in practice, documents whose contents are contained in other markup languages) is the entire purpose of CSS. It’s what CSS is for. It’s the sole reason CSS was invented.

        • LouisLazaris

          This technique still does that. The CSS is not in the HTML, it’s still separate, so it’s not as bad as you’re implying. Just because the names have implications of presentation, doesn’t mean you’re mixing presentation with content.

          The only way to truly separate content from style is to never use a single class or id in your HTML, and just use descendants and combinators. But that’s pretty much a horror story.

          I suggest you watch Nicolas Gallagher’s talk a few years back:

          https://www.youtube.com/watch?v=XQWOKBBJ114

          And read his article on CSS architecture:

          http://nicolasgallagher.com/about-html-semantics-front-end-architecture/

          He discusses these concepts and techniques and shows that they’re not as bad as people have made them out to be.

  • Anthony Alexander

    I made a thing I called CSS++ a while back which is basically a .css with every possible* permutation of style attributes. The file (pre css3 ie shadows, radius, etc) is about 100k.

    I figured that it would make more sense because the size would be negligible once the file got cached but mainly because it sped up development time normally spent on creating specific classes just for legibility’s sake.

    You end up with code like:

    Once you’re done laying out the page, you can always use some pre-processor to convert the “class” list into a single class

    CSS:

    /* containers */
    .relcnt{position:relative;}
    .abscnt{position:absolute;}
    .stacnt{position:static;}
    .fixcnt{position:fixed;}
    .inhcnt{position:inherit;}
    .horizcntr{margin:0 auto;}

    /* width px */
    .wd0px{width:0px;}
    .wd1px{width:1px;}
    .wd2px{width:2px;}
    .wd3px{width:3px;}
    .wd4px{width:4px;}
    .wd5px{width:5px;}
    .wd6px{width:6px;}
    .wd7px{width:7px;}
    .wd8px{width:8px;}
    .wd9px{width:9px;}
    .wd10px{width:10px;}

    LINK:
    http://www.stlucia-homes.com/css/css++.css

    As for the separation of code from structure, I think it’s overkill for any kind of HTML development.

  • pbrienesse

    I am really struggling to understand the benefit of this approach. In particular how it applies the DRY principle (don’t repeat yourself). It would seem you are saving yourself from repetition in your css at the expense of repetition and code bloat in your html applying a host of classes to each element to accomplish your task.

    I also can’t see how this would apply to a responsive site. You might have a class of .right or .mr0 which applies in your widescreen layout but in your narrow screen you would have to overwrite these with your queries. You now have a class that says ‘right’ or margin-right 0 when what you might actually be applying is float:none or position: absolute or who knows what else same with margin its location and size may change with the layout. It is why I have always avoided using terms like ‘sidebar’ or ‘content-right’ when applying id’s to div’s they might not always be sidebars and they may not always be on the right. I think it confuses
    things. I prefer terms like primary and secondary or .feature-column (maybe i am being picky)

    I fully understand the benefit of helper classes and reusing chunks of css but they should be larger than one
    line that does one specific thing otherwise one of the other comments is right why don’t we just start writing style=

    I am largely self taught and have often viewed sitepoint articles as demonstrating industry best practices and giving me new ideas but I have concerns whenI see articles like this as to what message this might send to someone just starting out. Hopefully they don’t get the idea this is the best practice approach.

    • http://ahmadajmi.com/ Ahmad Ajmi

      Thanks for your feedback. The benefit to this article is to show something I used that enhanced my workflow and it might help others as well. The important thing to consider if you would start doing this is that this method require you to switch the context from spending most of the time editing your CSS, instead you will switch to templates instead based on what’s already exist in CSS. The idea is to abstract repeating visual patterns to be used everywhere in any context. (How many times the float property you can find in any CSS file?). If it’s not working well in some cases in cases you can use your normal methods to write CSS. See for example the grid solution it works very well by abstracting some reusable classes and then you use them in templates. I always try to be open and flexible as much as I can to use new tools and adapt them based on my workflow.

  • LouisLazaris

    Thanks for your thoughts Jens, but I’m afraid you couldn’t be more wrong. :)

    First, there is nothing “harmful” about a CSS technique. CSS is not a weapon that harms people. No matter how bad you write it!

    Your #1 suggestion is itself nonsense. Nobody should use an ID in a stylesheet, the same way that nobody should use eval in JavaScript (barring some really rare edge case, but that doesn’t apply to IDs.) IDs have no use as selectors. Not one. There’s nothing you can do with an ID that you can’t do with a class. They’re utterly useless.

    Your #2 suggestion is nothing but theory. What is the purpose of keeping the HTML “clean”? What exactly does that accomplish? If the developer understands the modules he or she has created, having 2 or 3 classes on a single element will make the codebase as clean as you claim the HTML is supposed to be. The point of this article is to encourage small CSS, and a little extra HTML allowing the developer to build pieces that can be chunked together to form elements. Like Lego blocks. But your claim for cleaner HTML is just that. What is the point of it? Because it looks pretty? Why exactly is that beneficial?

    With proper documentation, and use of developer tools, the technique above should not be difficult at all to adopt.

    In one of your articles, you mention that the clean HTML will somehow lead to more accessibility and semantics. That is completely wrong. Screen readers do not choke on elements that have more class names. But you know that, and yet you still claim that the HTML will be more accessible with fewer classes. I’m sorry but that’s misinformation. :)

    But all of this being said, the author here is not promoting the idea of just going nuts with classes without a plan. The idea here is to have a documented set of one-responsibility modules that you can reuse anywhere, without touching the CSS.

    And regarding “presentational HTML”: It’s a nonsense phrase. So-called “presentational HTML” does nothing to harm semantics or accessibility. I don’t know who made up the phrase “presentational HTML” but it might be the same person that created XHTML. :)

    • http://cssmojo.com/ Thierry Koblentz

      Hi Louis,

      I see you guys are getting the “same old” comments. Not semantic, same as inline styles, yada, yada ;)

      Anyway, I wanted to mention something following this statement:

      > Nobody should use an ID in a stylesheet

      Actually, it makes a lot of sense to use an ID with atomic classes. This is because it allows these classes to overwrite styles coming from “other” rules.

      Imagine this:

      .my-box p {
      margin: 10px;
      }

      or even this:

      .my-list .list-item {
      margin: 10px;
      }

      or this:

      .button.primary-button {
      margin: 10px;
      }

      Using an ID, we can make sure that our atomic classes always overwrite generic styles:

      #atomic .M-20 {
      margin: 20px;
      }

      The “beauty” of atomic classes is that they do not “bleed”, they only style the element to which they are applied to (narrow scope). And there is no guessing, authors know what purpose these classes serve and also know (for sure) that they are not being overwritten by some other rules… somewhere… in some style sheets…

      • LouisLazaris

        Interesting. Thanks for mentioning that. Yeah, I suppose if we’re talking about the inner-inner parts of a particular module, then I guess the harm would be minimal.

        However, I would also argue that you can avoid that by simply avoiding descendants and chaining altogether. But even I don’t do that, so I’m not sure that’s a solution.

  • LouisLazaris

    And my apologies that your comment didn’t appear right away. Because of the links, it got flagged and we only approved it in the past half hour.

  • LouisLazaris

    That’s interesting because I’ve actually had thoughts about that sort of thing, but it just seems so ridiculous on first look.

  • david2m

    I agree with you Jens. It worries me seeing an article like this on a site which has a big audience. I guess horrible CSS will continue to be produced and passed on for years to come.

  • http://ricardozea.me/ Ricardo Zea

    I’ve used this technique extensively in the past, I just named it /*OOCSS*/ because the way I saw these classes were more like objects than “helpers”. This technique was something I came up with in my own, so in some way it feels nice to see the same concept being used by others.

    But I don’t use this technique anymore, it just doesn’t work as intended.

    You either spend too much time guessing what classes to create or if you’re going to use someone else’s classes you spend too much time learning their classes, and hoping that the one you need is already there so you don’t have to create it.

    Too much time wasted.

    Then we have the situation of the HTML ultra-classitis syndrome like . Oh boy.

    If you’re working by yourself, on your own and no one else is going to touch your code, do WTF you want :). But if you’re working in a team, you should think twice before making a fellow Web Designer/Dev’s life less happy.

    We all know how traumatizing it is to reverse-engineer someone else’s code. Finding something like this in a CSS file would only create enemies for life, or at least until you recognize the mistake.

    One thing I know for sure: Creating variables for white and black (or for any color that has an HTML name) is completely unnecessary.

    To go even further, I’m in the crossroads of dropping the use of CSS grids for this short value: flexbox.

    In this is yet another reason why helper classes like .float-left, .float-right, .half-width, etc. make this technique more and more unnecessary.

    Best of luck to those who dare venture this path.

    • http://ahmadajmi.com/ Ahmad Ajmi

      Choosing the class names will be based on the UI architecture, not mainly from other peoples code, every project is much different form another. (Mapbox example).

      I joined a team before and they were using this on the project and I was able to create new components from the classes they created before. The same goes with a fellow Designer.

      And as Thierry mentioned `It’s tools not rules`. It may not be best for some people and some workflows.

      • http://ricardozea.me/ Ricardo Zea

        If you plan to create helper classes every single time you start a new project, what happen to DRY?

        Regarding your past experience, good for you. Realize you were lucky. That doesn’t happen often.

        You lost me with the tools and rules part, hehe.

    • LouisLazaris

      Hi Ricardo, I appreciate that you have tried this and have reasons for not wanting to use it. You said:

      You either spend too much time guessing what classes to create or if you’re going to use someone else’s classes you spend too much time learning their classes, and hoping that the one you need is already there so you don’t have to create it.

      The problems you’re describing are present in any CSS project, not just when using this technique. How often have you ever picked up a project created by someone else and figured out their stylesheet in a really short time? I would guess never. Dev tools make it easier, but that would be true even with the above technique.

      I’m not necessarily advocating this technique, but I don’t really see the drawbacks that others in this thread are supposedly seeing. This is a modular approach, just like any modular approach. It’s just taking it a few steps further. With any such approach, you’re going to spend time planning and you’re going to spend time understanding previously written code. Again, that’s true in any CSS project.

      But what’s the alternative in an inherited project, if you don’t go modular? Well, then you have one of two choices: (1) Rewrite the whole code base (all the best with asking for the budget for that) or (2) Just adding new unique selectors to the bottom of the existing stylesheet, adding more bloat, and hoping you don’t have specificity wars (all the best with that too).

      But what if you had a system like the one Ahmad describes, but a really well-documented one? With good CSS comments, or separate, easy-to-read documentation, would it really be so hard to pick up the gist of the modules used and work from there? The key is that they’re documented. If they’re not, then I agree, it would be difficult.

      But this is, unfortunately, the same argument we’ll have for any CSS architecture. There’s always the learning curve, there’s always the maintenance challenges, there’s always the forethought challenges.

      • http://ricardozea.me/ Ricardo Zea

        Hello Louis, Thanks for your feedback.

        Indeed, it’s a problem that happens in any CSS project. What I’m saying is that this methodology doesn’t help much in that regard, in trying to understand someone else’s code at least when the initial author(s) have no CSS methodology.

        You say this is a modular approach, I see it as a “granular” approach and with so much minuscule detail in trying to guess what “grains” to create so you/we can put those grains (classes) in the HTML, is too much time wasted. Keep in mind that the guessing part here is what’s killer in terms of efficiency.

        That’s what I’ve experienced and that’s why I don’t use this technique anymore.

        Truth be told, if I ever encounter a project that had this approach but it was well done, that’s certainly something incredibly helpful, can’t deny that, since I’d be piggy-backing on the technique to enhance/extend the project.

        The problem I see, and I’m not being pessimistic, is that in my years of experience I haven’t met a single smart and intelligent CSS developer. At all. Well, maybe one and that was in the days before preprocessors.

        So honestly, I have zero to very-low hopes of ever seeing this technique implemented well if I ever come across it… unless I’m working with you or Ahmad :), that day I’d be a happy camper.

        • http://cssmojo.com/ Thierry Koblentz

          We’ve built https://my.yahoo.com/ based on atomic css. The weight of the style sheets is not even half of what we had before (actually, it’s close to a third). Also, the “atomic” style sheet is rarely edited which means we rarely invalidate the cache (not the case before as every push meant new style sheets). And there is less breakage because developers are not styling in the global scope – the classes they use only style their module, nothing else. Finally, after almost 2 years, the style sheets on my.yahoo have grown by less than 5%; that’s not even remotely possible using the classic semantic/SOC approach. There are also other advantages, but those are mostly relevant to Yahoo network (e.g. portability across products).

        • http://ahmadajmi.com/ Ahmad Ajmi

          That’s the point of this method is by creating abstract classes for reusing in different places, for example why making some thing like this http://cl.ly/image/2G2u0p0h1Y2z (body .card-block.photo .item_content .body > .caption > .container > h1.js-adjust) :), this code issues can be fixed by any modular approach not just Helpers. If we can create a single class for the gradient part for example and plug it in cards, user profile header or any other place depending on the UI. This will prevent bloat CSS and write more organized code. On the other hand for the HTML part we will add this abstract class and form the first time I see the class name I will know, yes this is a class for adding gradient to the element. It’s my pleasure Ricardo :)

  • M S i N Lund

    This article is worse than useless.

    You have completely misunderstood how to use CSS, an now you are “teaching” others how to not understand it too.

    Whats next?
    An article on how to put all your java-script inside the onclick?
    How to build your SQL in the browser with java-script, and send it to the server to be run?

    Whoever put this article on this site, should be fired.

    • LouisLazaris

      I put the article on the site. And I don’t regret it one bit.

      I challenge you to provide for me a practical example, with a code demonstration, showing exactly why you think the advice in this article is bad, with an explanation of why the technique would have a poor effect on any one or more of the following:

      – Website development/maintenance
      – Semantics
      – Accessibility

      I don’t think you’re capable of explaining your position with that context. If you can, SitePoint will pay you $200 for it, and I’ll post it on SitePoint as a response to this article. If you don’t want your name on it, I’ll post it under my name with a notice at the top explaining that it was contributed.

      In fact, that challenge goes out to anybody.

      Just remember: The basis of the argument needs to be one of the three things mentioned above or else something else that I don’t know of that will have some detrimental effect in some major area. The reasons cannot be theoretical (i.e. “hey guys, don’t use presentational classes!” or “this is not semantic”), the reasons must be immediately practical in some way.

  • http://labofoz.com/ Oz Ramos

    How would you target the notices or boxes in JavaScript?

    My point is, you’re over-abstracting. Instead of using a million classes on each element, have a single class and add “anti-helper” classes when you need them. For example – and let’s be serious here – you’re never going to have anything other than white text on any of your notice classes. If for some reason you really do want red on blue then you can do “notice-bg red”.

    In this case, “red” is the helper class. There’s nothing helpful about any of the classes in “white p1 mb1 notice-bg”, especially since only 2 of those classes are meaningful. The fact that you have to shorten p1 and mb1 is an identifier that you use (repeat) it enough to warrant obfuscating the name.

    Your stylesheet might be bone DRY, but your HTML will end up soaking WET.

    • LouisLazaris

      The notices or boxes would be targeted with IDs or maybe even data- attributes. In this case, they’d be anything but classes.

      Or you could use a JS-only class, as discussed here. In fact, many people feel it’s necessary to do this now, to ensure you don’t break JS functionality when you add or remove a class.

  • http://fyfi.net Kristaps Ancāns

    Try to do mass replace for “right/background/static/white/black” whatever on static HTML site without regexp. That’s where it fails miserably by changing the content of pages/articles.

  • http://ricardozea.me/ Ricardo Zea

    Well, Yahoo is in a category of its own. If a methodology like this one has worked for you, that’s expected, you are Yahoo and you should be doing to notch dev work. What happens in Yahoo is not the norm because of the quality of developers found there.

    On the other hand something like this: , ouch!

    But if it works for you and everyone in the team(s), that’s awesome and serves as an example that if you REALLY know what you’re doing, this methodology can be very helpful.

  • Ezekiel Gabrielse

    A good methodology like BEM should be used over something like this. This _requires_ that you edit your markup to modify styles. Markup should be for templating. No style, no logic, just simple templates. It also requires you to copy and paste components if you want to say, use a widget that’s on the homepage on a subpage. That’s ridiculous. Instead, you could just create the component with simple classes, and be confident that it will look exactly the same on all pages it’s used on.

    This is also non-responsive. What if I used the float class on a small item that needed to be floated left on all sizes, but didn’t know that it _doesn’t_ float left on mobile, which then breaks my component? Should I create a new class called flt-lft-all? It’s confusing. It’s dirty. If you want to do something like this, do it in Sass with @extends, not the markup.

    If I inherited a project that uses this technique, I would be pretty upset. The whole movement towards modular CSS is **good**, but let’s keep it extensible in the CSS, not the markup. On the bright side, simple helper classes for text colors and text alignment can be good, as clients like to be crazy with color. I do this quite often. However, I’m against creating components solely using helper classes.

  • http://adriancarballo.me/ Adrian Carballo

    AMCSS takes this concept even further, by creating modules instead of helpers to get the job done, while maintaining a more semantic HTML.

    Example:

    Here all the classes are separate helpers that can be combined together, but make HTML cluttered, and it doesn’t quite follow DRY principles.

    AMCSS:

    Now you can style the elements that contain the [am-dialog] attribute and apply full-width and border-bottom to it, while using error and text-left and text-right as a modifier. It also has the advantage of being much more semantic and easy in the eye.

    More info http://amcss.github.io/

  • Sergey

    Why reinvent the wheel – http://bem.info/method/definitions/

  • LouisLazaris

    I’m not sure what you’re asking…? In my comment I as talking about changing a single element that has float left, not lots of elements.

  • David Smith

    I don’t doubt that there’s a need for this sort of thing, irrespective of the debate over how CSS “should” or “shouldn’t” be authored. I’ve worked on a few legacy sites over the last year and when required to make bug fixes/improvements have often found myself looking to see whether a previous developer has created helper classes like these that I can reuse. Because of the lack of standardization around how CSS files are organized in these projects, it’s often hard to find the helper classes (if they exist at all), but that doesn’t mean they’re not useful or necessary. I’d also argue that helper classes might actually increase the general maintainability of code, since you can tell just by looking at the markup how a particular section of the page is supposed to look. It might not be pretty but it’s almost certainly practical.

  • http://www.billyhalim.zz.mu Billy Halim

    This is the recommended techniques for re-usable code. Helper class is one of the most important part of CSS especially if it is implemented into CSS libraries or frameworks. This idea is great !!

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.