简体   繁体   中英

How to show text on image hover rather than text hover - CSS/SASS

I'm sure this is a simple fix but can't get my head around what I'm doing wrong. I'm trying to show the 'title-text' as well as reduce opacity of the image on hover of the image. I have the image opacity reduction down but can't seem to make the text appear unless I directly hover the text. Any help would be appreciated! Thank you

#work {
  .items {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 1rem;

    .item {
      position: relative;
      background: $dark-color;
      // overflow: hidden;

      &:after {
        content: '';
        position: absolute;
        display: block;
        background: inherit;
        opacity: 0;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }

      // bring in main color overlay
      &:hover:after {
        opacity: 0.3;
      }

      &-text {
        position: absolute;
        top: 50%;
        left: 0;
        bottom: 0;
        right: 0;
        opacity: 0;
        text-align: center;
        z-index: 1;
        color: #fff;
      }

      // bring in text on hover
      &-image:hover &-text {
        opacity: 1;
      }

      &-image:before {
        content: '';
        display: block;
        padding-top: 75%;
        overflow: hidden;
      }

      &-image img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: auto;
        line-height: 0;
      }
    }
  }

I think you can wrap the image and the text in a div:

<div class="wrapper">
    <img src="image.jpg">
    <p>Your Title</p>
</div>

<style>
    .wrapper {
        position: relative;
        overflow: hidden;
    }
    .wrapper img {
        display: block;
        max-width: 100%;
        line-height: 0;
    }
    .wrapper p {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0;
        z-index: 2;
    }
    .wrapper:hover img {
        opacity: 0.6;
    }
    .wrapper:hover p {
        opacity: 1;
    }
</style>

If I understand you correctly, what you are trying to do can not be done with HTML/CSS alone. You would have to use JavaScript for such an effect.

Here is an example using jQuery which adds the class.darken to.item on hover. This will not work in your case without you rewriting your code, but you get the idea. You can of course add whatever in those two functions:

<script>
    (function(){
        jQuery(".item").hover(
            function() {
                jQuery(this).addClass('darken');
            }, function() {
                jQuery(this).removeClass('darken');
            }
        );
    })();
</script>

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