Search code examples
cssreactjsstyled-components

Fail to locate first-child and last-child at the same time using styled component


Just play around styled component recently and just wonder why I cannot use first-child and last-child at the same time which I can apply similar concepts when I using SCSS

What I want to do is to have customized style based on whether they are the first or last child of RowWrapper but no luck. Just want to know whether I have missed some concepts? Thank you very much in advance.

Reference link:

  1. sandbox link using styled component

  2. Testing link using SCSS

const RowWrapper = styled.div`

  :first-child {
    border: solid 1px black;
    color: red;
  }

  :last-child {
    border: solid 1px red;
    color: green;

    span {
      font-size: 22px;
    }
  }
`;
`


Solution

  • You're applying the pseudo-classes to the RowWrapper component itself. To apply them to the children, prepend a >:

    const RowWrapper = styled.div`
      >:first-child {
        border: solid 1px black;
        color: red;
      }
    
      >:last-child {
        border: solid 1px red;
        color: green;
    
        span {
          font-size: 22px;
        }
      }
    `;