如何在图像悬停而不是文本悬停上显示文本 - CSS/SASS

我确信这是一个简单的修复,但无法理解我做错了什么。我试图显示“标题文本”并减少图像悬停时图像的不透明度。我降低了图像不透明度,但除非直接悬停文本,否则似乎无法显示文本。任何帮助,将不胜感激!谢谢


#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;

      }

    }

  }


慕丝7291255
浏览 37回答 2
2回答

至尊宝的传说

我认为你可以将图像和文本包装在 div 中:<div class="wrapper">&nbsp; &nbsp; <img src="image.jpg">&nbsp; &nbsp; <p>Your Title</p></div><style>&nbsp; &nbsp; .wrapper {&nbsp; &nbsp; &nbsp; &nbsp; position: relative;&nbsp; &nbsp; &nbsp; &nbsp; overflow: hidden;&nbsp; &nbsp; }&nbsp; &nbsp; .wrapper img {&nbsp; &nbsp; &nbsp; &nbsp; display: block;&nbsp; &nbsp; &nbsp; &nbsp; max-width: 100%;&nbsp; &nbsp; &nbsp; &nbsp; line-height: 0;&nbsp; &nbsp; }&nbsp; &nbsp; .wrapper p {&nbsp; &nbsp; &nbsp; &nbsp; position: absolute;&nbsp; &nbsp; &nbsp; &nbsp; top: 50%;&nbsp; &nbsp; &nbsp; &nbsp; left: 50%;&nbsp; &nbsp; &nbsp; &nbsp; transform: translate(-50%, -50%);&nbsp; &nbsp; &nbsp; &nbsp; opacity: 0;&nbsp; &nbsp; &nbsp; &nbsp; z-index: 2;&nbsp; &nbsp; }&nbsp; &nbsp; .wrapper:hover img {&nbsp; &nbsp; &nbsp; &nbsp; opacity: 0.6;&nbsp; &nbsp; }&nbsp; &nbsp; .wrapper:hover p {&nbsp; &nbsp; &nbsp; &nbsp; opacity: 1;&nbsp; &nbsp; }</style>

qq_笑_17

如果我理解正确的话,你想要做的事情不能仅用 HTML/CSS 来完成。您必须使用 JavaScript 才能达到这样的效果。下面是一个使用 jQuery 的示例,它在悬停时将 .darken 类添加到 .item 中。如果不重写代码,这在您的情况下将不起作用,但您明白了。您当然可以在这两个函数中添加任何内容:<script>&nbsp; &nbsp; (function(){&nbsp; &nbsp; &nbsp; &nbsp; jQuery(".item").hover(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jQuery(this).addClass('darken');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jQuery(this).removeClass('darken');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; })();</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5