Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS select a class preceded by another class

Reading CSS documentation I'm trying to create a selector for a class preceded by another class:

<div class="AAAAA">
      <div class="CCCC"></div>
</div>
<div class="AAAAA">
      <div class="BBBB"></div>
      <div class="CCCC"></div>
</div>

I need to create a selector for .CCCC preceded by .BBBB, here my code:

.CCCC {
    width: 100px;
    height: 20px;
    border: 1px solid #000;
}

.CCCC~.BBBB {
    width: 10px;
    border: 1px solid #000;
}

So in my example the first div with CCCC class whould have a width of 100px, the second div with CCCC that id preceded by the div with class BBBB should have a width of 10px.

Any idea why this is not working?

like image 881
Bagbyte Avatar asked Jun 28 '13 20:06

Bagbyte


People also ask

How do I select another class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

What is complex selector CSS?

The h2 ~ p selector is a general sibling selector that looks for p elements that follow, and share the same parent, of any h2 elements. In order for a p element to be selected it must come after any h2 element.

How do I select a previous sibling in CSS?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2. 1.


1 Answers

You need to reverse your order. Note, this will select all .CCCC that are siblings following .BBBB.

.BBBB ~ .CCCC {
    width: 10px;
    border: 1px solid #000;
}

If you only want the next one, which must immediately follow it, then this:

.BBBB + .CCCC {
    width: 10px;
    border: 1px solid #000;
}

It is helpful to remember that with the current capabilities of CSS, the very last item in your selector string is always going to be the item you are actually selecting and applying the properties to (if a parent selector ever comes about, then that may not be so). So your incorrect .CCCC ~ .BBBB should have flagged you as incorrect because the .BBBB is the last item, but you were wanting to change the .CCCC.

like image 54
ScottS Avatar answered Oct 05 '22 01:10

ScottS