图像顶部的文本无需 Z-index 即可工作,为什么?
我想显示一个字幕文本,运行在图像的顶部,与底部(包含图像的 DIV)对齐。
我原以为我需要使用 Z-Index,但由于某种原因它不需要使用。我真的很想明白为什么。
这是 HTML:
<div class="latest-item">
<img src="images/latest-image-placeholder.png" alt="latest-image-placeholder"/>
<div class="latest-item-copy">Bad schools, flawed justice create crime. Test Bad schools, flawed justice create crime. Test </div>
</div>
这是相应的 CSS:
.latest-item {
height: 130px;
background-color: fuchsia;
margin-bottom: 20px;
overflow: hidden;
position: relative;
}
.latest-item-copy {
width: 220px;
/* Fallback for web browsers that doesn't support RGBa */
background: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);
bottom: 0px;
position: absolute;
padding-left: 5px;
padding-right: 15px;
padding-top: 2px;
padding-bottom: 4px;
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
-webkit-box-sizing:border-box; /* Safari */
font-family: Georgia, Times New Roman, serif;
font-size: 14px;
line-height: 18px;
color: #F1F1F1;
font-weight: bold;
}
这是它的输出: https://i.sstatic.net /Hdl9l.png
I want to display a subtitle text, running over the top of an image, aligned to the bottom (of the DIV containing the image).
I was expecting I'd need to use Z-Index but for some reason it works without. I'd really like to understand why.
Here's the HTML:
<div class="latest-item">
<img src="images/latest-image-placeholder.png" alt="latest-image-placeholder"/>
<div class="latest-item-copy">Bad schools, flawed justice create crime. Test Bad schools, flawed justice create crime. Test </div>
</div>
And here's the corresponding CSS:
.latest-item {
height: 130px;
background-color: fuchsia;
margin-bottom: 20px;
overflow: hidden;
position: relative;
}
.latest-item-copy {
width: 220px;
/* Fallback for web browsers that doesn't support RGBa */
background: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);
bottom: 0px;
position: absolute;
padding-left: 5px;
padding-right: 15px;
padding-top: 2px;
padding-bottom: 4px;
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
-webkit-box-sizing:border-box; /* Safari */
font-family: Georgia, Times New Roman, serif;
font-size: 14px;
line-height: 18px;
color: #F1F1F1;
font-weight: bold;
}
And here's what it outputs: https://i.sstatic.net/Hdl9l.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您绝对定位某个项目时,它将将该元素从文档流中拉出。这与浮动元素时发生的情况相同。它们会自动放置在具有更高 z-index 的不同“层”中。
When you position an item absolutely, it pulls the element out of the document flow. It's the same thing that happens when you float an element. They automatically get placed in a different "layer" that has a higher z-index.
因为您使用的是
position:absolute
Because you're using
position: absolute