I have the following markup:
<div class="c1">
<div class="c2">
<div class="c3">
<input>
<textarea></textarea>
</div>
<input>
<textarea></textarea>
</div>
</div>
I want to match the input
and textarea
elements from the div.c3
with only one CSS rule. I'm using
div.c1 .c2 .c3 input,textarea { border: 1px solid #f00; }
but this matches all textareas, not only the one cotnained in the c3
div.
Is this possible, or must I write separate CSS selectors for each element?
Look at http://jsfiddle.net/Bp3qn/1/ for the live example.
I updated http://jsfiddle.net/Bp3qn/3/
I only need the input and textarea contained in the c1->c2->c3 containers to be highlighted, not other combinations.
Yes, you can use what's known as :nth-child selectors. In this case you would use: li:nth-child(3n) { // Styling for every third element here. }
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator. There are four different combinators in CSS: descendant selector (space)
The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").
You don't need the other elements in the selector, unless you only want to match .c3
if it is within div.c1 .c2
:
.c3 input,
.c3 textarea {
/* that's it! */
}
If you do (per your edit), use this:
div.c1 .c2 .c3 input,
div.c1 .c2 .c3 textarea{
border: 1px solid #f00;
}
Demo: http://jsfiddle.net/wesley_murch/Bp3qn/6/
after edit: thats what i'm trying to avoid (my real stylesheet is a lot more complex and css rules are longer, and its getting hard to read)
In that case, to make things easier just add another class to that .c3
like this:
<div class="c3 special">
.c3.special input,
.c3.special textarea{
border: 1px solid #f00;
}
Demo: http://jsfiddle.net/wesley_murch/Bp3qn/7/
If you MUST have the selector as small as possible and there are no other children of .c3.special
, just use the star selector (almost never recommended):
.c3.special * {border: 1px solid #f00;}
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