Reputation: 6623
What's the simplest way to write a CSS selector that matches
#id.X .X a
for all X
?
Currently I'm manually specifying it for each X
I need, however it'd be much nicer to write a blanket statement and not have to edit the css each time I add a new X
.
Edit: The trimmed HTML this is for:
<div id="id" class="X">
<ul>
<li class="projects">...</li>
<li class="music">...</li>
<li class="resume">...</li>
<li class="contact">...</li>
</ul>
</div>
Where X is one of projects
, music
, etc. The purpose of having the class in the enclosing div
be equal to the class of one of the subobjects is to apply some style to one of the particular list elements. The reason I want to do it this way rather than having something like an active
class is that it makes my template files much more readable.
Upvotes: 1
Views: 228
Reputation: 14123
Current CSS does not provide means to avoid enumeration of all parent/child-class combinations in your case. So either your template should be more complicated while CSS is less complicated, or vice versa. Marking current element with class like active
or cur
is most universal and widely used solution.
Upvotes: 1
Reputation: 6623
I solved this by not trying to do this with CSS alone. Instead I modified the code to use an active
class and then just matched that. It made my templating more complicated, but in the end it's a better solution.
To be clear, I now have something like:
<div id="id">
<ul>
<li class="active">...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
Upvotes: 2
Reputation: 72261
Since you want a class
that is a child of the same class
as the basis for the target, I think you have three options, the first being the method you are using.
The second would be adding some extra into the HTML (a second class on the second object only when it is nested) like so:
CSS
.nestedA a {... blah ...}
HTML
<div id="id" class="X"><div class="X nestedA"><a></a></div></div>
So it shrinks your CSS, but expands your HTML, requiring you to code it (knowing it is nested, either by hand or by javascript detection).
The third is to prefix any classes that you intend this for and use the attribute start selector (IE8+ with DOCTYPE) like so (note the beginning portion must be separated by a hyphen):
CSS
.na-X {... X class blah ...}
[class|=na] [class|=na] a {... blah ...}
HTML
<div id="id" class="na-X"><div class="na-X"><a></a></div></div>
Upvotes: 0
Reputation: 17753
If you can use a naming pattern so that the class starts with, contains, or ends with a certain string, you could use the attribute selectors
Starts with
#id[class^="foo"] *[class^="foo"] a { color: red; }
Contains
#id[class*="foo"] *[class*="foo"] a { color: red; }
Ends with
#id[class$="foo"] *[class$="foo"] a { color: red; }
Fiddle using starts with: http://jsfiddle.net/TufaD/
An alternate strategy would be to assign a common class to all the elements you wish to style that way.
Upvotes: 0