【问题标题】:How to write a conditional css pseudo-element with styled-components?如何使用样式组件编写条件 CSS 伪元素?
【发布时间】:2022-11-15 21:00:22
【问题描述】:

我正在尝试使用条件伪元素编写样式组件,但它似乎不起作用。这是正确的语法吗?

背景:我正在努力做到这一点,如果 isSelected === true,第二个红色边框会出现在我的 div 周围(一个带有黑色边框的矩形框)。

非常感谢!

const CardContainer = styled.div(
    (props) => css`
        align-self: center;
        margin: auto;
        width: 80%;
        height: 100%;
        background: rgb(222, 222, 222);
        border-style: solid;
        border-width: 0.1rem;
        box-shadow: 4px 4px 8px rgba(183, 183, 183, 0.25);

        ${props.isSelected &&
        css`
            &::before {
                border-color: red;
                border-style: solid;
                border-width: 0.1rem;
            }
        `}
    `
);

【问题讨论】:

  • 使用这个({isSelected}) => isSelected && (css &::before { 边框颜色:红色;边框样式:实心;边框宽度:0.1rem; } )

标签: css reactjs styled-components pseudo-element


【解决方案1】:

它似乎不起作用。

语法本身没问题,但是您缺少 content 属性。 content 是必不可少的,因为除非指定,否则元素不会出现。

&::before {
    border-color: red;
    border-style: solid;
    border-width: 0.1rem;
    content: 'abc'; // it can be anything, even empty string
}

https://codesandbox.io/s/sad-sound-j5czon?file=/src/App.js:385-506

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2021-06-08
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2021-09-29
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多