【问题标题】:Unable to target nth child of styled component无法定位样式化组件的第 n 个子级
【发布时间】:2020-12-12 13:30:42
【问题描述】:

我正在尝试定位样式组件的 3 个子 divs,但我无法弄清楚我的语法有什么问题,并且样式组件文档似乎没有很好地涵盖这一点.我的代码是:

const HamburgerButton = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    min-height: 60%;
    min-width: 50px;
    border-radius: 8px;
    &:nth-child(1){
        width: 32px;
        min-height: 3px;
        background-color: red;
    }
    &:nth-child(2){
        width: 32px;
        min-height: 3px;
        background-color: red;
    }
    &:nth-child(3){
        width: 32px;
        min-height: 3px;
        background-color: red;
    }
`

const MobileNav = () => {

    const [open, setOpen] = useState(false)

    return (
        <MobileNavContainer>
            <Name>
                <h1>Josh Bangle</h1>
            </Name>
            <HamburgerButton>
                <span />
                <span />
                <span />
            </HamburgerButton>
        </MobileNavContainer>
    );
}

nth-child(2) 选择器似乎出于某种原因设置了 HamburgerButton 组件本身的样式,所以我只能想象这是一个语法问题,尽管谷歌搜索对我没有任何帮助。

【问题讨论】:

    标签: css reactjs sass styled-components


    【解决方案1】:

    const HamburgerButton = styled.div`
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        min-height: 60%;
        min-width: 50px;
        border-radius: 8px;
        & span:nth-child(1){
            width: 32px;
            min-height: 3px;
            background-color: red;
        }
        & span:nth-child(2){
            width: 32px;
            min-height: 3px;
            background-color: red;
        }
        & span:nth-child(3){
            width: 32px;
            min-height: 3px;
            background-color: red;
        }
    `

    在 & 和 : 之间放置一个空格告诉代码注意子组件。以您在上面编写的方式,它告诉代码查找第 n 个 HamburgerButton。如果你想引用任何第 n 个子元素,你也可以编写我上面没有跨度的代码

    & :nth-child(2){
      color: red;
    }

    【讨论】:

      【解决方案2】:

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

      nth-child 根据元素在组中的位置为元素设置样式(多年来,这让我困惑了一百万次)。 HamburgerButtonMobleNavContainer 中的第二个元素,它被设置了样式。您想将该类添加到跨度中。

      【讨论】:

      • Ahhhh,所以它不针对您正在应用第 n 个子选择器的元素的特定子元素,而是针对最高级别父元素的第 n 个子元素? > * 选择器怎么样?我改用了它,它正确地设计了所有 3 个跨度,这只是好运吗?大声笑
      • @JoshBangle &gt; 以直接后代为目标,因此结合通配符,您可以定位按钮的所有子元素。您可以将它与 nth-child 一起使用,但我认为将样式直接应用于 span 会更简洁。更容易调试。
      猜你喜欢
      • 2019-05-29
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2018-12-24
      • 2020-03-18
      • 1970-01-01
      相关资源
      最近更新 更多