0

Supoose you have something like

<div class="base"> <div> ... <div class="ok"> <div> ... <div class="ok"></div> ... </div> </div> ... </div> </div> 

Here I've shown just a couple of DIVs, but it can be any level deep (note the ...)

So the question is: How can I style the first element with the class okwithout knowing how deep it is nested ?

Here is a DEMO in which you can see I style all the DIVs with the class ok

1
  • are your divs all nested, or there are some siblings? Commented Jul 12, 2016 at 14:55

2 Answers 2

3

there is no selector for that, but there is override workaround: you can apply some css to all .ok and then reset on all nested .ok

div { margin: 5px; padding: 5px; border: 1px solid green; background-color: #fff; } .ok { background-color: gray; } .ok .ok{ background-color: #fff; }
<div> ... <div class="ok"> ... <div class="ok"> ... <div class="ok"> ... <div> ... </div> </div> </div> </div> </div>

Sign up to request clarification or add additional context in comments.

3 Comments

This assumes that, with the exception of "the first one", all elements that are members of that class will be descendants of "the first one". That is true of the example in the question, but it isn't clear if that is the case universally.
true, we shall ask
In my specific case I need to style the first ok not the ones nested deeper, meaning that this works for me :)
2

CSS provides no functionality to select an element based on anything that appears in the document after its start tag. Not descendants, not later siblings, and not later siblings of its ancestors.

You'd need to use JavaScript for this. Something along the lines of:

document.addEventListener("DOMContentLoaded", function(event) { document.querySelector(".ok").classList.add("ok-first"); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.