Don't miss our ROI, Data Quality and Peace of Mind webinar with Forrester Analyst, Richard Joyce on June 28th!

 

What we currently have in CSS is the use of IDs, classes, pseudo-selectors, and elements. With HTML5 and CSS3, what if I told you there was another option? What I’ve begun using at InfoTrust, inspired by a former coworker (tbremer https://github.com/tbremer), is using data-attributes to control CSS and add another layer of abstraction that benefits specificity in CSS.

css.jpg


[data-button] { 
    background-color: grey;
    border: 1px solid black;
    color: black;
}

[data-button="primary"] { 
    background-color: blue;
}

[data-button="large"] { 
    height: 40px;
    width: 120px;
}

One of the benefits of this approach is the separation of your style guide from your class structure. Who likes looking at classes like this:


<button class=”btn btn-large btn-primary”>Button</button>

Repeating elements like this takes up space and makes your code look complicated, and difficult to type accurately.

Using the data attribute, which is a valid HTML5 selector and can be targeted by both CSS and Javascript easily (IE11+), it encapsulates the element and helps to keep the markup clean:


<button data-button=”large primary”>Button</button>

Much better looking. Also, since the data-attribute is not as specific as a class or ID, you have flexibility and can still customize your styles for different modules or pages within your application.


.secondary {
    border: 1px solid DarkBlue;
}


<button data-button=”large primary” class=”secondary”>Button</button>

This leaves your IDs or classes to do more important things, like deal with layout or positioning, while the visual is left to the attribute and can be easily repeatable, keeping your HTML/CSS files small.


<button data-button=”large primary” id=”login” class=”float-right”>Button</button>

Down the road when dealing with updates to the styleguide or refactors, you are able to avoid verbose CSS naming structures and can have a more fluid style guide. The possibilities are endless with this approach and in my opinion offers better control of your styles and gives developers a more semantic approach to writing their HTML and CSS.

 

Join thousands of subscribers.

No sales pitches, no spam, and an easy one-click unsubscribe.

About The Author: InfoTrust is a web analytics company and a Google partner. Visit us at http://infotrustllc.com to learn more.