如何使用Angular 2添加背景图像伪元素“之后”内容?

时间:2018-07-24 07:42:41

标签: javascript css angular sass

我正在尝试从Angular的html中将URL图像传递到CSS上,但我无法做到这一点:

我的CSS是:

card-profile_visual {
      height: $visual-height;
      overflow: hidden;
      position: relative;
      background: linear-gradient(to bottom, darken(#545559, 10%), saturate(darken(#3A4A7B, 2%), 20%), saturate(darken(#3A4A7B, 15%), 20%));
      &:before,
      &:after {
        display: block;
        content: '';
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 0;       
        background: url(myUrl) no-repeat center center/cover;
        opacity: 0.5;
        mix-blend-mode: lighten;
      }

    }

我的html是:

<div class="card-profile_visual" [style.background-image]="'url('+offer.photo_url+')'"></div>

我如何实现将offer.photo_url传递给CSS:

背景:url(myUrl)无重复中心居中/封面;

非常感谢

3 个答案:

答案 0 :(得分:1)

使用ngStyle并与CSS Variables一起使用,如下所示:

代替:

CSS:

card-profile_visual {
      height: $visual-height;
      overflow: hidden;
      position: relative;
      background: linear-gradient(to bottom, darken(#545559, 10%), saturate(darken(#3A4A7B, 2%), 20%), saturate(darken(#3A4A7B, 15%), 20%));
      &:before,
      &:after {
        display: block;
        content: '';
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 0;       
        background: url(myUrl) no-repeat center center/cover;
        opacity: 0.5;
        mix-blend-mode: lighten;
      }

    }

HTML:

<div class="card-profile_visual" [style.background-image]="'url('+offer.photo_url+')'"></div>

使用此功能:

CSS:

card-profile_visual {
      height: $visual-height;
      overflow: hidden;
      position: relative;
      background: linear-gradient(to bottom, darken(#545559, 10%), saturate(darken(#3A4A7B, 2%), 20%), saturate(darken(#3A4A7B, 15%), 20%));
      &:before,
      &:after {
        display: block;
        content: '';
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 0;       
        background: var(--my-image) no-repeat center center/cover;
        opacity: 0.5;
        mix-blend-mode: lighten;
      }
    }

HTML:

<div class="card-profile_visual" [ngStyle]="{'--my-image': ' + offer.photo_url + '}"></div>

希望它能对您有所帮助。

答案 1 :(得分:1)

您可以在url属性中使用content

content: url(imageUrl);

答案 2 :(得分:0)

尝试一下

<div class="card-profile_visual" [style.backgroundImage]="'url('+offer.photo_url+')'"></div>

要在CSS的伪元素中添加背景图片,您可以这样做

.card-profile_visual:after{
  background: url(myUrl) no-repeat center center/cover;
}
相关问题