我建议使用伪元素代替覆盖元素。因为不能在封闭的 img 元素上添加伪元素,所以您仍然需要包装 img 元素。
LIVE EXAMPLE HERE -- EXAMPLE 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,0,0.6);
opacity: 0;
transition: all 1s;
-webkit-transition: all 1s;
}
将鼠标悬停在伪元素上时使用1 的不透明度以促进过渡:
.image:hover:after {
opacity: 1;
}
END RESULT HERE
如果你想在悬停时添加文字:
对于最简单的方法,只需将文本添加为伪元素的 content 值:
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;
}
如果content 的值为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,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;
}