0

I want to change opacity of an image when hover and show a text in middle of the image in same time.

My code is HTML:

<div class="col-md-4 j-t">
    <div class="middle">
        <div class="text-middle">Play</div>
    </div>
</div>

CSS:

.middle {
    transition: .5s ease;
    opacity: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    text-align: center;
}

.text-middle {
    background-color: white;
    color: black;
    font-size: 16px;
    padding: 16px 32px;
}

.j-t {
    height: 315px;
    background: url("pictures/golden_cut.jpg") center center no-repeat;
    background-size: cover;
    transition: .5s ease;
    backface-visibility: hidden; 
    opacity: 1;
}

.j-t:hover {
    opacity: 0.3;
}

.j-t:hover .middle{
    opacity: 1;
}

When used as is the text in the middle is also covered with opacity 0.3 from the image. I want the text in middle to have opacity 1.

Please help.

Artur Ferfecki
  • 148
  • 1
  • 2
  • 15
  • This has been discussed before: https://stackoverflow.com/questions/7241341/can-i-set-an-opacity-only-to-the-background-image-of-a-div – nylki Jul 21 '18 at 16:07

2 Answers2

0

don't set opacity on hover, rather change the background-color using background: rgba(0, 0, 0, 0.4)

ujjwal verma
  • 307
  • 3
  • 10
  • Not really what I was looking for, I still want to see the image in background. `background: rgba(0, 0, 0, 0.4)` changes the background to gray. – Artur Ferfecki Jul 21 '18 at 16:15
  • you can add a div over the top of the image, equal in size and set its background to that specified above. That's what i generally do. – ujjwal verma Jul 21 '18 at 16:18
0

Sorry my code is probably a little off since untested, but I've dealt with this problem lots. Any child of a container will be effected by the opacity of the parent. Instead move text-middle outside of middle, and make your j-t column relatively positioned. Then position text-middle on top of middle using positioning (middle and text-middle will be positioned in relation to the parent (j-t col). Then your :hover opacity will only affect .middle and not .text-middle

<div class="col-md-4 j-t">
    <div class="middle"></div>
    <div class="text-middle">Play</div>
</div>


.middle {
    transition: .5s ease;
    opacity: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    text-align: center;
}

.text-middle {
    position: absolute;
    top: -50%;
    background-color: white;
    color: black;
    font-size: 16px;
    padding: 16px 32px;
}

.j-t {
    position: relative;
    height: 315px;
    background: url("pictures/golden_cut.jpg") center center no-repeat;
    background-size: cover;
    transition: .5s ease;
    backface-visibility: hidden; 
    opacity: 1;
}

.j-t:hover {
    opacity: 0.3;
}

.j-t:hover .middle{
    opacity: 1;
}
James Allen
  • 969
  • 4
  • 16