仅在悬停时显示按钮

E.O*_*wen 12 html css sass

我已经阅读并尝试了其他解决方案来解决我的问题,但似乎都没有.

我有3张图片,每张图片都在他们自己的4列div中.我设置了css过渡,以便当用户的鼠标悬停在图像上时,这些图像从灰度渐变为彩色.我现在需要在悬停时出现一个按钮.我附上了一张图片来说明我的意思.

在此输入图像描述

这里是我的HTML和CSS的中间4列的片段.

--------------------- HTML ---------------------

<div class="small-4 columns">
    <img src="/wp-content/themes/adamslaw/assets/img/woman.png">
    <a class="button" href="/jane/">View Jane's Profile</a>
</div>
Run Code Online (Sandbox Code Playgroud)

--------------------- CSS ---------------------

.greyish {
background: $smoke !important;
h1 {
    margin: rem-calc(100) 0 0;
}
img {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  transition:.5s;
}

img:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
  .button:hover {
    display: inline-block;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:我使用SCSS,因此看起来很奇怪,嵌套的CSS规则.

H4r*_*ris 15

干得好:

.button {
    display: none;
}

img:hover + .button, .button:hover {
    display: inline-block;
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,我们使用相邻的兄弟css选择器+.选择器非常简单:在图像"悬停"上,您选择.button(它的兄弟)并显示它.在这里,我添加了.button:hover这样一来,当用户"悬停"按钮时,它会使其保持可见(当用户将鼠标移到按钮上时防止闪烁效果).


DBS*_*DBS 8

你可以使用一个简单的方法img:hover + .button来选择链接(+如果匹配.button选择器,则选择下一个元素)

.button {
  display: none;
}
img:hover + .button {
  display: inline-block;
}
Run Code Online (Sandbox Code Playgroud)
<div class="small-4 columns">
  <img src="http://placehold.it/350x150">
  <a class="button" href="/jane/">View Jane's Profile</a>
</div>
Run Code Online (Sandbox Code Playgroud)

或者,如果按钮不在图像上,则可以:hover在包装元素上使用,这样可以避免在您想要单击按钮时图像不再悬停的问题(当您尝试单击按钮时按钮会消失,如见上例)

.button {
  display: none;
}
.wrapper:hover img {
  /* Change the filter in here */
}
.wrapper:hover .button {
  display: inline-block;
}
Run Code Online (Sandbox Code Playgroud)
<div class="small-4 columns">
  <div class="wrapper">
    <img src="http://placehold.it/350x150">
    <a class="button" href="/jane/">View Jane's Profile</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)