Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css: does repeating the same class on an element change any behavior?

Tags:

html

css

Mostly out of curiosity, I would like to know if there are any edge cases that can arise from cases like:

<span class="class1 class2 class3 class2 class4">...</span>

(class2 is listed twice)

or

<span class="class1 class2 class3 class2 class2 class2 class3 class4 class4 class3">...</span>

(a more extreme version of the same)

This is obviously messy css and not ideal, but are there any edge cases this creates?

like image 377
Nick Knowlson Avatar asked Jan 12 '12 00:01

Nick Knowlson


People also ask

Can you use the same CSS class on multiple elements?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

Can you use the same class name on multiple elements?

Different Elements Can Share Same Class Different HTML elements can point to the same class name.

What is the important rule in CSS and why should you generally avoid it?

The !important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

Which of the following affects CSS specificity?

Duplicating id, class, pseudo-class or attribute selectors within a compound selector will increase specificity when overriding very specific selectors over which you have no control.


1 Answers

No, none whatsoever, unless you have the habit of using the class attribute:

[class="class1 class2"] {
    /* ... */
}

instead of:

.class1.class2 {
    /* ... */
}

which is terrible practice, of course.


Also, although your question isn't tagged javascript, note that if only the first instance of a class is removed and an unlimited number added, say:

function addClass(element, cls) {
    element.className += ' ' + cls;
}

but

function removeClass(element, cls) {
    return element.className.replace(cls, ' ');
}

this will cause problems in more ways than one.

like image 173
Ry- Avatar answered Sep 30 '22 11:09

Ry-