< h1>覆盖图像



我试图弄清楚如何将H1放在图片顶部。我尝试了在Stackoverflow上找到的多种方法,但我仍然无法绕过它。

html:

<div class="container">
    <div class="mainImg">
        <h1> Title </h1>
        <img src="img" alt="picture" />
    </div>
</div>

CSS:

    .mainImg {
    position: relative;
    left: 0;
    top: 0;
    background: green;
}
.mainImg h1 {
    z-index: 2;
    position: absolute;
    top: 30%;
    left: 0;
    right: 0;
    font-size: 20px;
    width: 100%;
    height: 26px;
    padding: 0;
    margin: 0;
    text-align: center;
    background: red;
}
.mainImg img {
    z-index: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background:green
}

如果您的容器(Mainimg)除了绝对定位的元素之外没有其他内容,则必须为其设置宽度和高度。这两个子元素都绝对放置了容器的内容流。图像仅具有宽度和高度值的百分比,以及取决于其容器的位置值,因此容器没有宽度和高度,它不占用空间:

.mainImg {
    position: relative;
    left: 0;
    top: 0;
    background: green;
    width: 300px;
    height: 200px;
}
.mainImg h1 {
    z-index: 2;
    position: absolute;
    top: 30%;
    left: 0;
    right: 0;
    font-size: 20px;
    width: 100%;
    height: 26px;
    padding: 0;
    margin: 0;
    text-align: center;
    background: red;
}
.mainImg img {
    z-index: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background:green
}
<div class="container">
    <div class="mainImg">
        <h1> Title </h1>
        <img src="http://placehold.it/400x300/0fb" alt="picture" />
    </div>
</div>

<style type="text/css">
   .mainImg {
    position: relative;
    left: 0;
    top: 0;
    background: green;
}
.mainImg h1 {
    z-index: 2;
    position: absolute;
    top: 30%;
    left: 0;
    right: 0;
    font-size: 20px;
    width: 100%;
    height: 26px;
    padding: 0;
    margin: 0;
    text-align: center;
    background: red;
}
.mainImg img {
    z-index: 0;
    width: 100%;
    height: 100%;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background:green
}
</style>
<div class="container">
    <div class="mainImg">
        <h1> Title </h1>
        <img src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="picture" />
    </div>
</div>

最新更新