elemnt:悬停 - 文字和背景

时间:2016-04-22 11:35:14

标签: css

我悬停它时需要在图像上显示文字,我还需要它来影响不透明度。

看一下这支笔http://codepen.io/anon/pen/NNBgbQ

 <div class="flex-menu">
 <div class="menu-container">
 <img class="menu-image" src="http://www.libbyroach.ca/wp-content/uploads/2014/11/Adams-Sandwich.jpg" alt="Sandwitch">
 <div class="menu-description">

 <h4>Sandwitch</h4>
 <p>Powder marshmallow marshmallow brownie carrot cake candy bonbon. Sweet sugar plum gummies caramels tart carrot cake tiramisu cheesecake. Cheesecake biscuit jelly beans. Jelly-o icing chocolate macaroon. </p>
 </div>
 </div>
 </div>

我正在寻找的结果:

将鼠标悬停在上方,图片会更改其不透明度,文字会显示在其中间 - 任何文字,不一定是当前标题和段落。

2 个答案:

答案 0 :(得分:1)

使用'position:abolsute定位文本div以覆盖图像是开始。

.menu-container div获取position:relative以提供定位上下文。

然后将:hover触发器切换到包装器以立即触发两者。

&#13;
&#13;
.flex-menu,
.menu-container,
.menu-image {
  width: 500px;
}
.menu-container {
  position: relative;
}
.menu-description {
  display: none;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
.flex-menu {
  background-color: #fd5c63;
}
.menu-image {
  transition: all 0.3s ease 0s;
  display: block;
}
.flex-menu:hover .menu-image {
  opacity: 0.2;
}
.flex-menu:hover .menu-description {
  display: block;
}
&#13;
<div class="flex-menu">
  <div class="menu-container">
    <img class="menu-image" src="http://www.libbyroach.ca/wp-content/uploads/2014/11/Adams-Sandwich.jpg" alt="Sandwitch">
    <div class="menu-description">

      <h4>Sandwitch</h4>
      <p>Powder marshmallow marshmallow brownie carrot cake candy bonbon. Sweet sugar plum gummies caramels tart carrot cake tiramisu cheesecake. Cheesecake biscuit jelly beans. Jelly-o icing chocolate macaroon.</p>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用position: absolute;

将文字放在图片上

我已将:hover.menu-image移至.menu-container,某些转换更改为更好看:

&#13;
&#13;
.flex-menu,
.menu-container,
.menu-image {
  width: 500px;
}
.flex-menu {
  background-color: #fd5c63;
}
.menu-image {
  opacity: 1;
  display: block;
  transition: opacity 300ms ease-in-out;
}
.menu-container:hover .menu-image {
  opacity: 0.2;
}
.menu-container {
  position: relative;
}
.menu-description {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 8;
  transition: opacity 300ms ease-in-out;
  opacity: 0;
}
.menu-container:hover .menu-description {
  opacity: 1;
}
&#13;
<div class="flex-menu">
  <div class="menu-container">
    <img class="menu-image" src="http://www.libbyroach.ca/wp-content/uploads/2014/11/Adams-Sandwich.jpg" alt="Sandwitch">
    <div class="menu-description">

      <h4>Sandwitch</h4>
      <p>Powder marshmallow marshmallow brownie carrot cake candy bonbon. Sweet sugar plum gummies caramels tart carrot cake tiramisu cheesecake. Cheesecake biscuit jelly beans. Jelly-o icing chocolate macaroon.</p>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;