<h1>覆盖图片

时间:2017-03-14 16:44:55

标签: html css

我试图找出如何将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
}

2 个答案:

答案 0 :(得分:1)

如果您的容器(mainIMG)没有除绝对定位元素之外的其他内容,则必须为其设置宽度和高度。通过绝对定位它们,两个子元素都在容器的内容流之外。图像只有百分比宽度和高度值,加上位置值取决于其容器,因此没有容器的宽度和高度它不占用空间:

&#13;
&#13;
.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
}
&#13;
<div class="container">
    <div class="mainImg">
        <h1> Title </h1>
        <img src="http://placehold.it/400x300/0fb" alt="picture" />
    </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
<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>
&#13;
<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>
&#13;
&#13;
&#13;