I would like to know more about pseudo-classes and the like. Is it possible to somehow select using 2, 3, 4 ... etc elements? Well, for example, there are 4 diva with a class of .example and I need to apply some styles to it. Is it possible to do so without creating additional id and classes?
1 answer
You can use the pseudo-class :nth-child :
.example:nth-child(1) { // ΡΡΠΈΠ»ΠΈ } .example:nth-child(2) { // ΡΡΠΈΠ»ΠΈ } .example:nth-child(3) { // ΡΡΠΈΠ»ΠΈ } .example:nth-child(4) { // ΡΡΠΈΠ»ΠΈ } UPD. Added an example:
.example { margin-bottom: 10px; border-bottom: 1px solid #ccc; } .example:nth-child(1) { color: red; } .example:nth-child(2) { color: green; } .example:nth-child(3) { color: blue; } .example:nth-child(4) { color: purple; } p, h1 { color: #000000; } <div class="example"> ΠΠΈΠ² β1 <p>ΠΠΎΡΠ΅ΡΠ½ΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΡΠΎ ΡΠ²ΠΎΠΈΠΌ ΡΠ²Π΅ΡΠΎΠΌ</p> </div> <div class="example"> ΠΠΈΠ² β2 <h1>ΠΠΎΡΠ΅ΡΠ½ΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΡΠΎ ΡΠ²ΠΎΠΈΠΌ ΡΠ²Π΅ΡΠΎΠΌ</h1> </div> <div class="example"> ΠΠΈΠ² β3 <h3>ΠΠΎΡΠ΅ΡΠ½ΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Ρ Π½Π°ΡΠ»Π΅Π΄ΠΎΠ²Π°Π½ΠΈΠ΅ΠΌ</h3> </div> <div class="example"> ΠΠΈΠ² β4 <h4>ΠΠΎΡΠ΅ΡΠ½ΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Ρ Π½Π°ΡΠ»Π΅Π΄ΠΎΠ²Π°Π½ΠΈΠ΅ΠΌ</h4> </div> - I heard about it ... But for some reason, during layout, it is not the elements that I need that stand out. Child elements are highlighted (for example, in each of the 4 divs there are some h1, p - they stand out). - Andrew
- @ Andrei show your code (css and html) - Alexey Ten
- @MasterAlex, correct: nt h -child. @Andrey, it all depends on the markup. Sometimes
:nth-child, sometimes:nth-of-type, and sometimes you need to apply a pseudo-class to parent elements, and not directly to those elements to which you want to apply CSS properties. - Deonis - @Andrey, the child elements inherit some styles of the parent, if they do not have these styles in css, added an illustrative example to the answer. - MasterAlex
- @Deonis, yes, yes, I already fixed it when I did the example :) - MasterAlex
|