Suppose we have such elements:

<div class="block"> <p> <span> .... </span> </p> </div> 

To get to the p element with respect to the div with the block class, we do this:

 .block > p { border: 1px solid black; } 

What do you do if you need to get to the span element relative to the div element with the block class?

    2 answers 2

    To do this, you do not need to put

     div.block span {color: red} 
     <div class="block"> <p> <span> .... </span> </p> </div> 

    Or like this:

     div.block > p > span {color: red} 
     <div class="block"> <p> <span> .... </span> </p> </div> 


    Add. information

    To address the neighbor, you need to put + :

     .block {width: 50px; height: 50px; background-color: black;} .block + .block {background-color: red;} 
     <div class="block"> </div> <div class="block"> </div> 

    And that would apply to all the right neighboring elements, put ~ :

     .block {width: 50px; height: 50px; background-color: black;} .block ~ .block {background-color: red;} 
     <div class="block"> </div> <div class="block"> </div> <div class="block"> </div> <div class="block"> </div> 

    To address a particular element, put :nth-child :

     .block {width: 50px; height: 50px; background-color: black;} .block:nth-child(3) {background-color: red;} 
     <div class="block"> </div> <div class="block"> </div> <div class="block"> </div> <div class="block"> </div> 

    • thanks for the details - perfect
    • @perfect, or did you have something else I entered? - Yuri
    • that's exactly what i wanted - perfect
    • @perfect, and for common development. Now they use such a classification system: ru.bem.info/methodology - Yuri
    • @perfect BEM is a methodology, not a classification. + - immediate neighbor selector on the right. Select any neighbor on the right - ~ . - Vadim Ovchinnikov

    You can, as you wrote.

     .block > p > span { border: 1px solid black; } 

    And it is possible and so:

     .block span { border: 1px solid black; } 

    The first selector selects a direct descendant. Those. styles will be applied to all span elements that are in the p element, which, in turn, is nested in a container with the class .block.

    The second selector selects not direct descendants, but all. Those. styles are applied to all span elements that are nested in a container with a class .block no matter at what level.

    • Thanks for the tip, I thought this syntax is only jquery uses - perfect