Code Junkie Code Junkie - 9 months ago 48
CSS Question

CSS limit depth styles can be applied to elements

Does anybody know of a solution to limit the child depth when selecting an element with



.my-class div div:end(styles:here)

This would prevent having to add
classes to every single second div in the page while preventing styles from being passed on down to the third fourth etc. child.

Answer Source

You can specifically tell it to search only 1 level deeper with the > operator.

Consider the following example:

#target > p > span {
    background: red;

This will search #target for a direct child element <p>, and within that element, will search for a direct child element <span>. So if there is a nested <p> element, and a span inside of it, it won't be affected.

A very common use is for nested list items, where you want the main list to style, but the secondary list to not.

ul#parent > li /* Direct descendant. */
ul#parent > li > ul > li /* 2 levels deep descendant. */