Home > Software design >  Why cant I set opacity to background-image of a div?
Why cant I set opacity to background-image of a div?

Time:12-14

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

enter image description here

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()"
  
  (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?

CodePudding user response:

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  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()"
  
  (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?

  • Related