0

I have a div that has a background-image, I would like its hover effect to change its opacity without affecting the child element, in this case the <p>. I have seen similar answers to my question, but having a background does not work the answers. opacity to an element with background affects the children, I only want to affect the father

How can I solve that?

<div class="container_img">
  <p>
  this is a text 
  </p>
</div>

.container_img{
   position:relative;
   border:1px solid red;
   margin-top:-14px;
   display: table; 
   margin-top:2px; 
   width: 709px; 
   height: 141px;     
   background-image: url("https://i.imgur.com/VBOZfaY.png");
   background-image: url("https://i.imgur.com/VBOZfaY.png");
   background-repeat: no-repeat;
   background-size: 100% 100%;
}

.container_img:hover{
 background-color: transparent;
 opacity:0.5;
}

this is my code:

https://jsfiddle.net/t98mbxca/

unusuario
  • 151
  • 1
  • 13

2 Answers2

0

In this case opacity is working as expected as it changes the alpha channel for the element and all of its contents. You may need another approach. Looks like you just want a green gradient button?

I changed the div to a button and removed the p tag in the HTML.

For the background you can use pure CSS to create a linear-gradient as a background-image using rgba for the colors so you can change the alpha (opacity) on hover.

.container_img {
   height: 50px;
   line-height: 50px;
   padding: 0 60px;
   border-radius: 10px;
   font-size: 20px;
   cursor: pointer;
   background-image: linear-gradient(rgba(130, 167, 99, 1), rgba(102, 146, 63, 1));
}

.container_img:hover {
   background-image: linear-gradient(rgba(130, 167, 99, 0.5), rgba(102, 146, 63, 0.5));
}
<button class="container_img">
  this is a text 
</button>
BugsArePeopleToo
  • 2,976
  • 1
  • 15
  • 16
0

The easiest way, if you want to use an actual image, is to move your background image to a pseudo element.

.container_img {
  position: relative;
  border: 1px solid red;
  margin-top: -14px;
  display: table;
  margin-top: 2px;
  width: 709px;
  height: 141px;
}

p {
  position: absolute;
  left: 50%;
  font-size: 50px;
}

.container_img::before {
  content: '';
  background-image: url("https://i.imgur.com/VBOZfaY.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.container_img:hover::before {
  opacity: .5;
}
<div class="container_img">
  <p>
    this is a text
  </p>
</div>
Steven B.
  • 8,962
  • 3
  • 24
  • 45