微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

黑色透明覆盖图片悬停与只有CSS?

我试图添加一个透明的黑色覆盖图片,只要鼠标悬停在图像上只有CSS。这可能吗?我试过这个:

http://jsfiddle.net/Zf5am/565/

但我不能得到的div出现。

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
    <div class="overlay" />
</div> 

.image {
  position: relative;
  border: 1px solid black;
  width: 200px;
  height: 200px;
}
.image img {
  max-width: 100%;
  max-height: 100%;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  background-color: red;
  z-index: 200;
}
.overlay:hover {
  display: block;
}

解决方法

我建议使用伪元素代替overlay元素。因为伪元素不能添加到封闭的img元素,你仍然需要包装img元素。

LIVE EXAMPLE HEREEXAMPLE WITH TEXT

<div class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

对于CSS,在.image元素上设置可选尺寸,并相对定位。如果你的目标是响应图像,只是省略尺寸,这仍然可以工作(example).它只是值得注意的尺寸必须在父元素而不是img元素本身,see

.image {
    position: relative;
    width: 400px;
    height: 400px;
}

给子元素img元素宽度的100%的父,并添加vertical-align:top来修复认的基线对齐问题。

.image img {
    width: 100%;
    vertical-align: top;
}

对于伪元素,设置内容值并相对于.image元素绝对定位它。宽度/高度为100%将确保这适用于不同的img尺寸。如果要转换元素,请将不透明度设置为0,然后添加过渡属性/值。

.image:after {
    content: '\A';
    position: absolute;
    width: 100%; height:100%;
    top:0; left:0;
    background:rgba(0,0.6);
    opacity: 0;
    transition: all 1s;
    -webkit-transition: all 1s;
}

当悬停在伪元素上时,使用不透明度1,以便于转换:

.image:hover:after {
    opacity: 1;
}

END RESULT HERE

如果您要在悬停上添加文字

对于最简单的方法,只需添加文本作为伪元素的内容值:

EXAMPLE HERE

.image:after {
    content: 'Here is some text..';
    color: #fff;

    /* Other styling.. */
}

这应该在大多数情况下工作;但是,如果您有多个img元素,则可能不希望悬停时显示相同的文本。因此,您可以在data- *属性中设置文本,因此每个img元素都有唯一的文本。

EXAMPLE HERE

.image:after {
    content: attr(data-content);
    color: #fff;
}

使用attr(data-content)的内容值,伪元素添加.image元素的data-content属性中的文本:

<div data-content="Text added on hover" class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

你可以添加一些样式,并做这样的事情:

EXAMPLE HERE

在上述示例中,:after伪元素用作黑色覆盖,而before伪元素是字幕/文本。由于元素彼此独立,因此您可以使用单独的样式来实现更佳的定位。

.image:after,.image:before {
    position: absolute;
    opacity: 0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:after {
    content: '\A';
    width: 100%; height:100%;
    top: 0; left:0;
    background:rgba(0,0.6);
}
.image:before {
    content: attr(data-content);
    width: 100%;
    color: #fff;
    z-index: 1;
    bottom: 0;
    padding: 4px 10px;
    text-align: center;
    background: #f00;
    Box-sizing: border-Box;
    -moz-Box-sizing:border-Box;
}
.image:hover:after,.image:hover:before {
    opacity: 1;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。