首页 > 解决方案 > 带有 React 样式组件的伪元素

问题描述

我已经查找了几个答案,感觉就像我以完全相同的方式设置它,但它不起作用。

我的文档的 index.css 设置了一个渐变背景,效果很好。然后我有我的页脚,这也有效。但是问题来了,我想将 SVG 作为背景添加到页脚,并在其上设置不透明度。

如果我这样做,背景图像会出现,但整个页脚会受到不透明度的影响,这当然是一个不好的结果。

const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;
    background-image: url('/logo.svg');
    opacity: 0.25;
}
`

但是,如果我这样做,如果我只希望背景图像半透明而页脚的其余部分保持不透明,这似乎就是它应该如何工作,那么背景图像根本不会显示:

const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;
    
     &::before {
    content: "";
    background-image: url('/logo.svg');
    position: absolute;
    opacity: 0.25;
    }
}
`

我应该如何设置它以使背景图像是半透明的,但页脚的其余部分不是?

如果有帮助,这是我的页脚 JSX:

<Foot id="footer-page">
                    <Div>
                        <div className="container">
                            <div className="row">
                                <div className="col-lg-4 col-sm-12 text-center">
                                    <p className="lead">HUMAN RESOURCES SOLUTIONS></p>
                                    <img className="img-fluid" src="/assets/images/wbe-seal.png" alt="certified women owned business seal" />
                                </div>

                                <div className="col-lg-4 col-sm-12 text-center"><p className="lead">FOLLOW US ON <Span orange>SOCIAL MEDIA</Span></p>
                                        <A href="https://www.facebook.com" target="_blank" rel="noopener noreferrer"><i className="fab fa-facebook-square fa-3x px-2"></i></A>
                                        <A href="https://www.instagram.com" target="_blank" rel="noopener noreferrer"><i className="fab fa-instagram fa-3x px-2"></i></A>
                                        <A href="https://www.linkedin.com/" target="_blank" rel="noopener noreferrer"><i className="fab fa-linkedin fa-3x px-2"></i></A>
                                        <A href="https://twitter.com" target="_blank" rel="noopener noreferrer"><i className="fab fa-twitter-square fa-3x px-2"></i></A>
                                </div>
                            </div>
                        </div>
                    </Div>
                </Foot>

标签: cssreactjsstyled-components

解决方案


看起来您需要在使用&::before伪选择器的地方使用单个冒号 (:)。

此外,如果这不起作用,您可以尝试使用after伪选择器。

const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;
    
    &:before {
      content: "";
      background-image: url('/logo.svg');
      position: absolute;
      opacity: 0.25;
    }
}

推荐阅读