Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple classes be assigned to an element using a comma?

Tags:

css

Ive just come accross this on a website im working on.. its something ive not seen before and can't find any explanation of this anywhere so was hoping someone could explain.

So ive come accross an element that is marked up with 2 classes in the following format:

<div class = "class1, class2"></div>

Ive never seen multiple classes assigned to an element like this before.. it looks like a selector to me.. I would expect them to be added like this: (without comma)

<div class = "class1 class2"></div>

is this valid CSS I have just never come accross before or have i just found a slightly weird bug on the page?

like image 770
Ash Avatar asked Dec 05 '25 00:12

Ash


1 Answers

Just to add a little bit of extra information than the other answers so far:

  1. The correct syntax (like everyone is saying) is the second - space-separated.
  2. If you use the first (comma separated), then the classes with a comma directly after them won't be applied, but any other class will. For example:

<div class="class1, class2">

will apply class2 only to the div.

<div class="class1 class2,">

will apply class1 only

<div class="class1 , class2">

will successfully apply both classes.

<div class="class1,class2">

will load neither

Note that this extends for more than two classes: class="class1 class2, class3" will apply class1 and class3, for instance.

It transpires that any class name you try to add which contains an invalid or unescaped special character (see Here and here) will not load, but it doesn't stop the other valid class names from loading. Because classes are space separated, the DOM interprets "class1, class2" as two classes class1, and class2, and determines class1, to be invalid as , is a special character in CSS.

like image 189
Ieuan Stanley Avatar answered Dec 07 '25 15:12

Ieuan Stanley