4

Can anyone explain me what does the below css do?

.validate-error .validate-error {
  color: #cc2424;
  display: inline-block;
  margin-top: 5px;
}
.make-switch + .validate-error {
  margin-left: 10px;
}

In the first css i see the same class name used twice?. Is this css valid?. I came across this thread What is the difference between the selectors ".class.class" and ".class .class"? but unsure whether its applicable if we use the same class name twice?.

2
  • even .validate-error.validate-error (without space in between) is valid and sometimes is used as a hack to increase specificity, but that's the other case...
    – Jan Pi
    Commented Dec 18, 2020 at 11:51
  • @davidcondrey - no it wouldn't: it just means the class needs to exist once: .name.name would match class="name".
    – BeeOnRope
    Commented Sep 17, 2021 at 18:04

5 Answers 5

6

The first one styles child elements/descendant with the same class name:

<div class="validate-error">
    This color may be different from #cc2424
    <div class="validate-error">Has color #cc2424</div>
</div>

This means: The styles are applied/overwritten for child elements with the same class name.


The second one styles siblings:

<div class="make-switch"></div>
<div class="validate-error">Has left margin</div>
<div class="validate-error">Has no left margin</div>

That means: Only if .make-switch is followed by .validate-error the styles are applied to .validate-error.

Demo

Try before buy

2
.validate-error .validate-error {
  ...
}

This css targets a class .validate-error that is a descendant of .validate-error.

For example

<div class="validate-error">
    <div class="validate-error">
    </div>
</div>

Next css targets the class .validate-error when it is right next to .make-switch

.make-switch + .validate-error {
  ...
}
1

when selector parts are stuck together without whitespace it means it should all match the same element.

example: (should only match an element having both validate-error and other-class as classes)

.validate-error.other-class

when there is whitespace between them you are selecting an element that has other-class as a class and has a parent element with the validate-error class

the + in your second selector actually means you don't want a child of make-switch but you want the sibling element, but only if it has class validate-error

0

Yes it is valid. There are no rules in CSS preventing a class name appearing multiple times in a complex selector. There are no rules in HTML preventing two elements, one of which is a descendant of the other, from sharing membership of a class.

0

Id only should be unique, but classname we can use multiple times.

Not the answer you're looking for? Browse other questions tagged or ask your own question.