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?
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 (.)
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With