简体   繁体   中英

CSS Opacity on Rollover Image with Text, but No Opacity Change on Text

I have an image, with text on top. When I rollover the Image I want the opacity of the background image to lower, but not the opacity for the text above it.

I thought that since the text was in a span i could simply tell the span to have the opacity: 1 !important; however that doesn't seem to do the trick. Can anyone help?

Here is the JSFiddle: https://jsfiddle.net/zerojjc/xrwao8n9/

HTML:

<div class="boxThird">
    <a class="btnBox boxOne" href="<?php bloginfo('url'); ?>/" title="About Heath, Fania &amp; Co"><span>About</span></a>
</div>

CSS:

.boxThird {
    float: left;
    width: 33.33%;
    height: 400px;
    background: #000;
}
.boxThird span {
    margin-left: 25px;
    position: relative;
    top: 344px;
    text-decoration: none;
    border-bottom: 1px solid #fff;
}
.btnBox {
    display: block;
    text-align: left;
    color: #fff;
    text-shadow: 0px 0px 2px #555;
    text-transform: uppercase;
    text-decoration: none;
    font-weight: 400;
    font-size: 2em;
    letter-spacing: .125em;
}
.boxOne {
    height: 100%;
    width: 100%;
    background-position: center;
    background-size: cover;
}
.boxOne {
    background-image: url(https://i.imgur.com/izS0fLZ.jpg);
}
.boxOne:hover{
    opacity: 0.8;
}
.boxOne:hover span{
    opacity: 1 !important;
}

Opacity cascades, which means that if you have a span inside a div and they both have 0.8 opacity, the child-span would actually have 80% opacity of the parents 80% opacity (so IDK, 64% opacity). So by setting opacity: 1 to your span, you basically set it to the parents 0.8 opacity.

To prevent this, you can move the background image into a :before pseudo element and just change the :before opacity. You can see a working example here: https://jsfiddle.net/xr06hby2/

Relevant CSS:

.boxOne {
  position: relative;
}
.boxOne:before {
  content: '';
  background-image: url(https://i.imgur.com/izS0fLZ.jpg);
  background-position: center;
  background-size: cover;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 1;
  transition: opacity 0.3s;
}
.boxOne:hover:before{
  opacity: 0.3;
}

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