简体   繁体   English

<h1>重叠图像

[英]<h1> overlaying image

I'm trying to figure out how to place h1 on top of a picture. 我试图弄清楚如何将h1放在图片上方。 I've tried multiple ways found here at stackoverflow but I still can't get my head around it. 我已经尝试过在stackoverflow上找到的多种方法,但是仍然无法解决。

HTML: HTML:

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

CSS: 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
}

If your container (mainIMG) has no other content than those absolutely positioned elements, you have to set a width and height for it. 如果您的容器(mainIMG)除了绝对定位的元素之外没有其他内容,则必须为其设置宽度和高度。 Both child elements are outside of the content flow of the container by positioning them absolutely. 通过绝对定位两个子元素,它们都位于容器的内容流之外。 The image just has percentage width and height values, plus position values dependent on its container, so without width and height for the container it takes up no space: 图像仅具有百分比的宽度和高度值,以及取决于容器的位置值,因此,没有容器的宽度和高度,它就不会占用空间:

 .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