There is a conditional parent block with sections that are added and removed dynamically:

<div id="wrapper"> <section></section> <section></section> <section></section> ... </div> 

Is it possible to stylize the last odd section on pure css? That is, if the sections are even, then nothing happens, and if it is odd, then other styles are applied to the last section?

    2 answers 2

    To do this, you can use the last element pseudo :last-child and with the help of :nth-child select all the odd elements:

     section { display: block; width: 200px; height: 50px; margin-bottom: 5px; background-color: black } section:last-child:nth-child(2n+1) { background-color: red; } 
     <div id="wrapper"> <section></section> <section></section> <section></section> </div> 

    • Good, pulled the puzzle) - VostokSisters
    • when 6 selektov does not work - L. Vadim
    • 2
      @ L.Vadim, and nothing, that 6 element is even? - Yuri
    • so he should sort of paint in red fifth, on the question, or not - L. Vadim
    • one
      @ L.Vadim, 2n - we take two elements, 2n + 1 - we take the first of the two - Yuri

    Since the wording “last odd” does not imply that it will be both the last and the odd at the same time, here’s an alternative, which with any number of elements will highlight the last odd.

     section { height: 20px; margin-bottom: 10px; background: #000; } section:nth-last-child(-n+2):not(:nth-child(even)) { background: red; } 
     <div> <section></section> <section></section> <section></section> <section></section> <section></section> <section></section> </div> 

    • In my opinion, he clarified: "That is, if the sections are even, then nothing happens, and if it's odd, then other styles are applied to the last section." But your example is informative - Yuri
    • @Yuri yes, I saw. Added the answer solely for the knowledge base, if someone else will do a search on the issue. - Sasha Omelchenko