繁体   English   中英

<h1>重叠图像

[英]<h1> overlaying image

我试图弄清楚如何将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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM