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?
开发者_StackOverflowLook 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.
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;}
div.c1 .c2 .c3 input,.c3 textarea { border: 1px solid #f00; }
I know it's an old topic but I wanted to add some points on this because I just ended up here while trying to apply the same king of logic. And thanks to this question, I know now that we should reconsider that logic a bit.
First, the upvoted answer does solve the question but I don't understand why the use of .c1 .c2
classes in the CSS.
As @Wesley Murch first wrote, that should be enough:
.c3 input,.c3 textarea { /* that's it! */ }
It's also ok to specify a bit more with:
div.c3 input,
div.c3 textarea {
border: 1px solid #f00;
}
which is already the shorthand for:
div.c3 > input,
div.c3 > textarea {
border: 1px solid #f00;
}
But, IMO, unless you really have no control of what's inside your div
, you should simplify everything by just adding one more class in your HTML and then you'll also end up with only one rule which will be even a bit easier to read:
HTML update with one more class special-border-color
for exemple:
<div class="c1">
<div class="c2">
<div class="c3">
<input class="special-border-color">
<textarea class="special-border-color"></textarea>
</div>
<input>
<textarea></textarea>
</div>
</div>
CSS simple rule:
.special-border-color {
border: 1px solid #f00;
}
精彩评论