如何在React中使动态背景图像不透明?

时间:2018-04-25 03:51:09

标签: css reactjs gatsby

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

图像太亮了。我要么降低不透明度要么必须添加叠加。

更改不透明度将更改文本的不透明度。添加叠加层已将自身定位在锚点之上,使其无效。

如果您有兴趣,我正在使用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>;
...

Blog post image that is difficult to read

生成的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;
}

我知道this method,但我不知道如何将图片放入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伪类

1 个答案:

答案 0 :(得分:1)

U必须将叠加层作为内容的兄弟,并使其成为绝对。并且您还必须增加内容的z索引,以便它可以是交互式的。

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

试试这个

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