Dobob Dobob - 4 months ago 8
HTML Question

CSS selecting classes with different ids and vice versa

As you can see the CSS code below is repetitive but I am not fluent enough to simplify it.

<!-- CLASS then ID -->
.myClass#firstID {
background-color: #bbb;
}

.myClass#secondID {
background-color: #bbb;
}
.myClass#firstID:hover {
background-color: #000;
}

.myClass#secondID:hover {
background-color: #000;
}

<!-- ID then CLASS -->
#myID.firstClass {
background-color: #123456;
}

#myID.secondClass {
background-color: #123456;
}
#myID.firstClass:hover {
background-color: #111;
}

#myID.secondClass:hover {
background-color: #111;
}


Is there a way to stylize a class with multiple ids or an id with multiple classes in a single block without repeating ".myClass" or "#myID"?

Answer

The provided code is equivalent to this:

.myClass#firstID, .myClass#secondID {
    background-color: #bbbbbb;
}

.myClass#firstID:hover, .myClass#secondID:hover {
    background-color: #000;
}   

#myID.firstClass, #myID.secondClass {
    background-color: #123456;
}

#myID.firstClass:hover, #myID.secondClass:hover{
    background-color: #111;
}

It cannot be condensed much further.

Additionally, Sass provides nested selector functionality.

Comments