thelolcat
thelolcat

Reputation: 11545

Using data attributes instead of classes in CSS

HTML

<div data-foo> ... </div>

CSS

div[data-foo]{ ... }

Is this a good idea? Are there any drawbacks?

I think the data- approach makes sense when I have hundreds of "foo" elements, because the HTML markup size decreases (-3 characters for each element).

Upvotes: 1

Views: 3950

Answers (2)

Dave
Dave

Reputation: 46249

  • div[data-foo] is not supported in old IE (IE6, see here: http://www.quirksmode.org/css/selectors/)
  • div[data-foo] makes less semantic sense
  • class="foo" and data-foo will take up about the same space when DEFLATE-d. If you haven't set up your server to deflate, you should.
  • class=foo is only one character longer than data-foo even uncompressed, and is perfectly valid HTML.

Upvotes: 4

Mr. Alien
Mr. Alien

Reputation: 157314

It totally depends on you, for example elements must be having different attributes, so you need to define styles and even repeat some, instead I'll use a class which I can use for both, instead of using attribute selector which will limit my declared properties upto an element with that attribute, where you can freely use classes regardless of element attribute combination

.class { /* You can use this anywhere you need these properties */
   font-family: Arial;
   font-size: 13px;
}

Where as this will limit to ELEMENT-ATTRIBUTE combination

div[data-menu] { /* This will LIMIT you to a combination of div 
                    element having an attribute called data-menu */
    font-family: Arial;
    font-size: 13px;
}

Important : Specificity will make you a huge mess

Upvotes: 1

Related Questions