target first-child css styled-components

peter flanagan picture peter flanagan · Jan 2, 2019 · Viewed 24.9k times · Source

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>
)

Answer

Thinker picture Thinker · Jan 2, 2019

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 :)