target first-child css styled-components

60,967

Solution 1

Finally, I got your issue. The styled component confuses with the first two native p tag (from my perspective) and that's the reason why the CSS is not applied.

I will use a workaround like this:

const Text = styled.p`
    font-size: 12px;
    color: blue;
    &:nth-child(3) {
        margin-bottom: 20px;
        color: red !important;
    }
`;

By doing this, you are selecting the third child (which include the first two p tag) for the CSS

OR, you can do something like this: Adding a class name for the tag and giving CSS for that class.

const Text = styled.p`
  font-size: 12px;
  color: blue;
  &.colors {
    margin-bottom: 20px;
    color: red !important;
  }
`;

 <div>
    <p>I am just regular text</p>
    <p>Me too</p>
    <Text className="colors">Hello Joe</Text>
    <Text>Goodbye</Text>
</div>

Here is the demo

Hope it helps :)

Solution 2

Use like this

const Text = styled.p`
   font-size: 12px;
    > * {
      &:first-child {
         margin-bottom: 20px;
      }
    }
`;

Solution 3

There shouldn't be a space between the & and the :first-child

&:first-child {
    margin-bottom: 20px;
}

Solution 4

it's better to use :last-of-type on certain styled component instead of using :nth-child and it works perfectly

export default styled.div`
    :last-of-type {
        background: red;
    }`

const Text = styled.p`
    font-size: 12px;
    color: blue;
    &:nth-child(3) {
        margin-bottom: 20px;
        color: red !important;
    }
`;

Share:
60,967
peter flanagan
Author by

peter flanagan

javascript, ruby enthusiast

Updated on July 09, 2022

Comments

  • peter flanagan
    peter flanagan almost 2 years

    I am using styled-components and want to target the first child of Text, but am unable to do so.

    const Text = styled.p`
        font-size: 12px;
        &:first-child {
            margin-bottom: 20px;
        }
    `;
    
    ... component
    
    return(
       <div>
          <p>I am just regular text</p>
          <p>Me too</p>
          <Text>Hello Joe</Text> // this should have the margin bottom
          <Text>Goodbye</Text >
       </div>
    )