1

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

1
  • If the data-foo attribute serves no purpose whatsoever, then you should use classes instead. Commented Mar 31, 2013 at 16:06

2 Answers 2

4
  • 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.
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Are you suggesting that data attributes add specificity? In my case, this would be an advantage, because I want the styles that I apply to these elements should have the highest priority (if it would be possible, I'd isolate them from other elements with the same name)
@thelolcat Learn more about the specificity here coding.smashingmagazine.com/2007/07/27/…
@thelolcat: There's nothing in the spec that says an attribute selector must be accompanied by a type selector. An attribute selector is equal to a class selector in terms of specificity, but that alone is not a valid reason to use an attribute selector where a class selector makes more sense.
@Mr.Alien you should probably update the reasoning and conclusion in you answer knowing that you don't have to specify and element, just an attribute selector like [data-menu], as @BoltClock mentioned. I'm genuinely looking for cases where you need to use classes that custom or data-attributes wouldn't work. or even if there are performance or size/compressability implications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.