目标 first-child css styled-components

target first-child css styled-components

我正在使用 styled-components 并想定位 Text 的第一个 child,但我做不到。

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

&:first-child

之间不应有 space
&:first-child {
    margin-bottom: 20px;
}

我终于明白你的问题了。样式组件与前两个原生 p 标签混淆(从我的角度来看),这就是 CSS 未应用的原因。

我将使用这样的解决方法:

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

通过这样做,您正在为 CSS

选择第三个 child(包括前两个 p 标签)

或者,您可以这样做:为标签添加 class 名称并为该标签提供 CSS 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>

这里是demo

希望对您有所帮助:)

在特定样式的组件上使用 :last-of-type 比使用 :nth-child 效果更好

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;
    }
`;

这样使用

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