简体   繁体   中英

Why cant I set opacity to background-image of a div?

I have a list of components which I display like a grid, it looks like this:

在此处输入图像描述

So, each item is a component. The thumbnails are just background-images which I set dynamically in my html.

When hovering over them, some text appears on that box. The background image stays. Now my goal is to give that background-image some opacity. Sounds easy, but I dont know how to accomplish this and I tried already several approaches from other posts.

Here is my relevant html code:

<div
  *ngIf="!isFile()"
  class="image-container"
  (mouseenter)="onMouseHover()"
  (mouseleave)="onMouseLeave()"
  (click)="onDokumentClick()"
  [style.background-image]="'url(' + thumbnailPathGenerator() + ')'"
>

and thats my scss:

.image-container {
  border-radius: 4px;
  background-repeat: no-repeat;
  background-position: center center;
  box-sizing: border-box;
}

.image-container:hover {
  border-radius: 4px;
  box-sizing: border-box;
}

the url gets generated in the template, thats the challenge...

How can I set an opacity to my image-background?

In straight JS, HTML, CSS it would be something like this - the CSS variable --bg being set to the background image URL which can be picked up by the pseudo element styling:

 const div = document.querySelector('.image-container'); function thumbnailPathGenerator() { return 'https://picsum.photos/id/1015/150/150'; } div.style.setProperty('--bg', 'url(' + thumbnailPathGenerator() + ')');
 .image-container { border-radius: 4px; box-sizing: border-box; position: relative; }.image-container::before { content: ''; background-image: var(--bg); background-repeat: no-repeat; background-position: center center; box-sizing: border-box; position: absolute; width: 100%; height: 100%; top: 0; left: 0; }.image-container:hover::before { border-radius: 4px; box-sizing: border-box; opacity: 0.4; }
 <div class="image-container" style="width: 50vmin; height: 50vmin;"></div>

I don't myself use angular, but I believe you can now (since version 9) set a CSS variable like here:

<div
  *ngIf="!isFile()"
  class="image-container"
  (mouseenter)="onMouseHover()"
  (mouseleave)="onMouseLeave()"
  (click)="onDokumentClick()"
  [style.--bg]="'url(' + thumbnailPathGenerator() + ')'">
>

Note: I don't know what your mousenter and out functions do. Are they necessary if you have the opacity being dealt with by CSS?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM