首页 > 解决方案 > 如何在 React 中使动态背景图像不透明?

问题描述

我有博客文章,每篇文章都有封面图片。我想在我的帖子列表页面中使用这些图像作为实验,看看它是否会使页面活跃一点。

图像太亮。我要么希望降低不透明度,要么必须添加叠加层。

更改不透明度将更改文本的不透明度。添加叠加层会将其自身定位在锚点之上,从而使它们变得无用。

如果您有兴趣,我正在使用 Gatsby Casper 入门套件。

PostListing.jsx

...
<PostFormatting className={className} key={title} cover={cover}>
    <PostHeader>
        <h2 className="post-title">
            <Link to={path}>{title}</Link>
        </h2>
...

PostFormatting.jsx

...
const style = cover ? { backgroundImage: `url(${cover})` } : {};
return <article className={className} style={style}>{children}</article>;
...

难以阅读的博文图片

生成的 HTML

<article class="post" style="background-image: url(&quot;https://picsum.photos/1280/500/?image=800&quot;);">
    <header class="post-header">
        <h2 class="post-title">
            <a href="/blog/rewire-your-brain-7">Test Post</a>
        </h2>
    </header>
    <section class="post-meta">
        <span>
            <span class="tag"><a href="/tags/mindset">Mindset</a></span>
            <span class="tag"><a href="/tags/productivity">Productivity</a></span>
        </span>
        <time class="post-date" datetime="2017-06-27">27 June 2017</time> 
    </section>
    <section class="post-excerpt"><p>...</p></section>
</article>

CSS

我为 post 元素拥有的所有样式。

<element.style> {
    background-image: url(https://picsum.photos/1280/500/?image=800);
}

.home-template .content .post, 
.tag-template .content .post {
    background-color: rgba(0, 0, 0, .1);
    padding: 30px 50px 50px 50px;
}

.post {
    position: relative;
    width: 80%;
    max-width: 710px;
    margin: 4rem auto 0em auto;
    padding-bottom: 4rem;
    border-bottom: #1a232c 3px solid;
    word-wrap: break-word;
}

我知道这种方法,但我不知道如何将图像放入 after 伪元素。

div {
  width: 200px;
  height: 200px;
  display: block;
  position: relative;
}

div::after {
  content: "";
  background: url(image.jpg);
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}

注意:为伪类尝试Radium

标签: cssreactjsgatsby

解决方案


您必须将叠加层作为内容的同级,并使其成为绝对值。您还必须增加内容的 z-index,以便它可以交互。

在您的情况下,文章中的所有元素都应该分组并放在内容类中。

尝试这个

.parent{
  height:300px;
  padding:50px;
  position:relative;
}
.overlay{
  position:absolute;
  top:0;right:0;left:0;bottom:0;
  background-color:rgba(0,0,0,0.5);
  z-index:0;
}
.content{
  position:relative;
  z-index:1;
  font-size:25px;
  color:white;
}
<div class="parent" style="background-image:url(http://via.placeholder.com/350x150)">
  <div class="overlay"></div>
  <div class="content">Test Test</div>
</div>


推荐阅读