TAGS :Viewed: 16 - Published at: a few seconds ago

[ selecting all siblings except first ]

Is there a CSS selector that selects the compliment of .a + .b with respect to .a ~ .b?

In less mathy terms, I want to select all sibling elements that succeed an element, excluding its first sibling successor.

For example, in all dl lists, I have all dd elements colored a certain color. But in inline dl lists, I want to keep the first dd following a dt the same color, but all subsequent dds will be changed to another color. Below is my code, which is clearly not DRY. Is there a way to do it without re-defining the color again?

/* dl lists contain dd terms all colored light aqua */
dl > dd {
    background-color: #c0ffee;
}
/* inline dl lists have dd terms displayed inline and colored yellow-green */
dl.inline > dd {
    display: inline;
    background-color: #bada33;
}
/* however, in an inline dl list, the first dd succeeding a dt is colored normally */
dl.inline > dt + dd {
    background-color: #c0ffee;
}

enter image description here

Answer 1


Yes, You Can Select the Complement

In your simplified example, it would be this: .a + .b ~ .b. You "skip" the first .b by using it as the launching point for the general sibling selector.

If I understand your dd requirements, then it would be this:

/* dl lists contain dd terms all colored light aqua */
dl > dd {
    background-color: #c0ffee;
}
/* inline dl lists have dd terms displayed inline  */
dl.inline > dd {
    display: inline;
}
/* however, in an inline dl list, the first dd succeeding a dt is left 
   to be colored normally and all after it are colored yellow-green */
dl.inline > dt + dd ~ dd {
    background-color: #bada33;
}

But that requires each dt be in its own dl, otherwise you have issues. The general sibling selector is not going to help you if they are all under one list, because the dl.inline > dt + dd ~ dd is more specific than any following dl > dd.

So in Your Case

The solution is to keep from repeating code and having specificity not override under a single list is this:

/* dl lists contain dd terms all colored light aqua */
dl > dd,
dl.inline > dt + dd {
    background-color: #c0ffee;
}
/* inline dl lists have dd terms displayed inline  */
dl.inline > dd {
    display: inline;
    background-color: #bada33;
}