我建议使用伪元素代替overlay元素。由于伪元素不能添加到封闭的
img元素上,因此您仍然需要包装该
img元素。
<div > <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" /></div>
至于CSS,请在元素上设置 可选尺寸
.image,并相对放置它。如果您希望获得自适应图像,则只需省略尺寸即可,但仍然可以使用(示例)。值得注意的是,尺寸必须位于父元素上,而不是
img元素本身。
.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;}如果要在悬停时添加文本,请执行以下操作:
对于最简单的方法,只需将文本添加为伪元素的
content值即可:
.image:after { content: 'Here is some text..'; color: #fff; }在大多数情况下,这 应该 有效但是,如果您有多个
img元素,则可能不希望在悬停时显示相同的文本。因此,您可以在
data-*属性中设置文本,因此每个
img元素都有唯一的文本。
.image:after { content: attr(data-content); color: #fff;}随着
content中值
attr(data-content),伪元素添加从文本
.image元素的
data-content属性:
<div data-content="Text added on hover" > <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" /></div>
您可以添加一些样式并执行以下操作:
在上面的示例中,
: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;}


