如何在图像源不在CSS样式内的图像上应用线性渐变

时间:2019-10-19 15:41:02

标签: javascript css sass background gradient

我看到的解决方案是CSS url(image-path),然后是线性渐变,但是我有

class Example extends Component {
    render() {
        return (
            <div className="carousel__container">
                <Carousel infiniteLoop="true" autoPlay="true" showThumbs="false" showIndicators="false">
                    {this.props.items.map(movie => {
                    return  <div className="carousel__image" key={movie.id}><img src={`${this.props.MDBConfig.images.secure_base_url}original${movie.backdrop_path}`} alt={movie.title}/><h1 className="carousel__title">{movie.title}</h1></div>
                    })}
                </Carousel>
            </div>
        );
    }
}

图像源来自React内部,而不是来自CSS URL,因此,每当我应用线性渐变时,它都会被放置在所获取的图像后面。

有没有解决的办法?谢谢

1 个答案:

答案 0 :(得分:0)

您可以在图像上方使用绝对定位的伪元素(::before),并使用它显示渐变背景。

示例:

const Image = ({ movie }) => (
  <div className="carousel__image" key={movie.id}>
    <img src={movie.src} alt={movie.title}/>
    <h1 className="carousel__title">{movie.title}</h1>
  </div>
);

const movie = { id: 1, src: 'https://picsum.photos/500/200', title: 'demo' };

ReactDOM.render(
  <Image movie={movie} />,
  root
);
.carousel__image {
  position: relative;
  display: inline-block;
}

.carousel__image::before {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: repeating-linear-gradient(
    45deg,
    transparent,
    transparent 20px,
    #465298 20px,
    #465298 30px
  );
  pointer-events: none;
  content: '';
}

/** if you want the header above the gradient **/
.carousel__image h1 {
  position: relative;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>