我建议使用伪元素代替overlay元素。由于伪元素不能添加到封闭的img
元素上,因此您仍然需要包装该img
元素。
<div class="image">
<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;
/* Other styling.. */
}
在大多数情况下,这 应该 有效但是,如果您有多个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" class="image">
<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;
@R_214_2419@-sizing: border-@R_214_2419@;
-moz-@R_214_2419@-sizing:border-@R_214_2419@;
}
.image:hover:after, .image:hover:before {
opacity: 1;
}