0

I have some code that looks like this:

  .my-class {

      :nth-child(2) {

         padding-right: 15px;
         padding-left: 0;
   ...
   ...
}}

This works fine. The issues is that this also gets applied to all of .my-class's descendants.

So for example, if under .my-class I also have a <div className="test">...</div>, the padding above will also be applied to the second child of that div.

Is this how CSS works? How can i just make sure this applies to the second child of .my-class and nothing else?

disinfor
  • 10,865
  • 2
  • 33
  • 44
Gambit2007
  • 3,260
  • 13
  • 46
  • 86

2 Answers2

2

If you look at how your SCSS actually gets compiled, you'll see it gets compiled to:

.my-class :nth-child(2) {
  padding-right: 15px;
  padding-left: 0;
}

Because CSS cascades (hence cascading style sheet), your :nth-child(2) will affect every second child.

I changed the padding to the left side, so it can be seen.

.my-class :nth-child(2) {
  padding-right: 0;
  padding-left: 15px;
}
<div class="my-class">
  <div>
    first
    <div>
      first child
    </div>
    <div>
      second child
      <div>
        first - second child
      </div>
      <div>
        second - second child
      </div>
    </div>
  </div>
  <div>
    second
  </div>

</div>

If you want to stop this, you need to get specific on the what the :nth-child(2) should be applied to.

Like this:

.my-class > :nth-child(2) {
  padding-right: 0;
  padding-left: 15px;
}
<div class="my-class">
  <div>
    first
    <div>
      first child
    </div>
    <div>
      second child
      <div>
        first - second child
      </div>
      <div>
        second - second child
      </div>
    </div>
  </div>
  <div>
    second
  </div>

</div>

That essentially will only affect DIRECT children of .my-class.

Here's the SCSS:

.my-class {

       > :nth-child(2) {

         padding-right: 15px;
         padding-left: 0;

}}

Documentation for the direct child combinator >

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

disinfor
  • 10,865
  • 2
  • 33
  • 44
  • 1
    Great, many thanks for the detailed answer! – Gambit2007 Jan 03 '20 at 16:36
  • 1
    You're welcome!! I would recommend checking out all of the different selectors (if you haven't already), there are some fun ones. https://www.w3schools.com/cssref/css_selectors.asp – disinfor Jan 03 '20 at 16:37
0

you can do like this

.my-class {

   > :nth-child(2) {

     padding-right: 15px;
     padding-left: 0;

}}

the operator ">" means that you want just for himself