我假设你想把这个内容列成一个列表:
这里有几个主要的概念:相对定位以及它如何与绝对定位配合使用,源顺序以及你的居中技术。
当将position:relative;应用于盒子时,你在说“现在我是边界 - 对于任何在我内部绝对定位的东西”(除非它们是相对的,然后就像这样一直向下)- 因此,您要淡入的绝对定位覆盖物 - 绝对定位到相对盒子的一个或多个边缘。(大多数人使用top:0;left:0;) ---因此,绝对框不再处于“流动”状态,而是生活在其由相对父级确定的自己的魔力世界中。
源顺序:当堆叠时,你的html将从底部向上显示。因此,你的覆盖物应该在图像下面(按html顺序) - 你可以使用z-index - 但没有必要这样做。
负边距在这里并不真的很棒,也不需要。你可以把它们文本对齐居中。我会做一些测试,围绕着东西画边框,这样你就可以看到实际发生了什么。而且 - 我鼓励你在所有东西上使用box-sizing:border-box;
阅读:Border box
HTML
<ul class="thumbnail-list">
<li>
<a href="#" class="image-w">
<img alt="thumbnail"
src="http://placekitten.com/600/300" />
<div class="cover">
<h3>Title</h3>
<p>A little bit more about the thing</p>
</div>
</a>
</li>
</ul> <!-- .thumbnail-list -->
CSS
.thumbnail-list {
list-style: none;
margin: 0; paddingn: 0;
}
.thumbnail-list li {
float: left;
}
a {
text-decoration: none;
color: inherit;
}
.thumbnail-list .image-w {
display: block;
position: relative;
width: 16em;
}
.image-w img {
display: block;
width: 100%;
height: auto;
}
.cover {
position: absolute;
top: 0; right: 0;
bottom: 0; left: 0;
width: 100%;
height: 100%;
color: rgba(255,255,255,0);
text-align: center;
transition: all 1s linear;
}
.cover:hover {
background-color: rgba(0,0,0,.8);
color: rgba(255,255,255,1);
transition: all .2s linear;
}
.thumbnail-list h3 {
font-size: 1.2em;
}
.thumbnail-list p {
font-size: .9em;
}
Here is the code in action on jsfiddle