Reputation: 78981
For example my HTML is this
<ul>
<li>Sample 1</li>
<li>Sample 2
<ul>
<li>Sub 1</li>
<li>Sub 2</li>
<li>Sub 3
<ul>
<li>Grandsub 1</li>
<li>Grandsub 2</li>
<li>Grandsub 3
<ul>
<li>verySub 1</li>
<li>verySub 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Sample 3</li>
</ul>
I want to use different styles on every child <UL>
without defining any class or id on them.
I dont know how many child <ul>
might occur inside one another so inline css will not to the job
Is this possible?
Upvotes: 0
Views: 2080
Reputation: 2802
This uses jQuery, and cycles through a list of three background colours:
function nestedcolour(elements, level) {
if (elements.length > 0) {
var colour = ["#fafafa", "#fbf9ea", "#eeeeee"][level % 3];
elements.css('background-color', colour);
nestedcolour(elements.children("ul").children("li"), level + 1);
}
}
$(document).ready(function() {
nestedcolour($(".classofparentelement"), 0);
});
The .classofparentelement
is not really necessary, you can use any method to find the parent element(s).
Upvotes: 0
Reputation: 701
It looks like you want some way of programmatically defining your style. This is not possible using CSS alone. It does not support you defining your own symbolic names, let alone attempts to do something more 'programmery'. If you were able to generate your CSS dynamically then you could use this to work out the number of levels and algorithmically define the style each time
Otherwise the alternative is to put a maximum on the level of nesting (say 20 levels) and define a style for each one like artlung suggests. Most of the time the lower level definintions won't get used, but they will be there if you need them. This isn't perfect but it's the best you can do with writing directly in CSS.
Upvotes: 0
Reputation: 10713
If you don't know how many child UL/LI's there may be inside each other, then this won't be possible in CSS.
CSS doesn't support "fuzzy logic" such as: if there are over 5 <li>'s then do something.
Javascript Is the way forward me-thinks!
Upvotes: 0
Reputation: 34013
All you need is to specify each level like so:
<style type="text/css">
ul li { color: red; }
ul li ul li { color: blue; }
ul li ul li ul li { color: black; }
ul li ul li ul li ul li { color: green; }
</style>
No inline style
attributes, no classes required.
Works perfectly on the HTML snippet you provided. Keep in mind, that each successive level will inherit from the one before it. That's the whole idea of the "cascading" part of CSS, but I've burned myself forgetting margins at a lower level and having things go haywire.
Upvotes: 3
Reputation: 466
You can use the "Inline Styling" for each element to have different styles.
Here it is:
<ul style="property:value;">
<li>..</li>
</ul>
Upvotes: 0