CSS 如何在不使用位置的情况下将一个 div 覆盖在另一个 div 上:绝对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13036796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:36:15  来源:igfitidea点击:

How to overlay one div over another div without using position: absolute?

cssoverlaycss-positionmargin

提问by Dmytro

I have two divs with two images:

我有两个带有两个图像的 div:

<div id="div1">    

     <div id="div2">
         <img src="img1" />
    </div> 

    <img src="img2" /> 

</div>

Second one is some smaller than first. How can I put second image on first image without using

第二个比第一个小一些。如何在不使用的情况下将第二张图像放在第一张图像上

#div2{
    position: absolute;
}

I need to get similarresult but without using position absolute property;

我需要得到类似的结果,但不使用位置绝对属性;

The main issue is that there are a lot of other elements, in parent div, not only div2.

主要问题是在父div中还有很多其他元素,而不仅仅是div2。

回答by Robert Koritnik

Negative margins

负利润

You can do lots with negative margins. I've created an examplewith just two images without any divs.

你可以做很多负利润。我创建了一个只有两个图像而没有任何 div的示例

img {
    display: block;
}
.small {
    margin: -202px 0 0 0;
    border: 1px solid #fff;
}
.small.top {
    position: relative;
    margin: 0 0 -202px 0;
}
<img src="http://www.lorempixel.com/300/300">
<img class="small" src="http://www.lorempixel.com/200/200">
And some text
<img class="small top" src="http://www.lorempixel.com/200/200">
<img src="http://www.lorempixel.com/300/300">
And some more text

回答by Andy

My question to you is why must you do this WITHOUT

我对你的问题是为什么你必须这样做

#div2 {
    position: absolute;
}

If the problem you are encountering is because it's absolute to the page and not the div then make sure #div1 has the following:

如果您遇到的问题是因为它是页面的绝对问题而不是 div,那么请确保 #div1 具有以下内容:

#div1 {
    position:relative;
}

回答by saad

Its not a good approach to use negative margins. Especially when email templating, gmail reject negative margin and positions. So another way is

使用负边距不是一个好方法。特别是在电子邮件模板时,gmail 拒绝负保证金和头寸。所以另一种方式是

    <div class='wrapDiv'  style='width: 255px;'>
           <div class='divToComeUp' style='
                    float: left;
                    margin-top: 149px; width:100%;'>This text comes above the .innerDiv  
according to the amount of margin-top that you give</div>

           <div class='innerDiv' style='width:100%; height:600px'>
               Inner div Content
           </div>

    </div>

回答by Kevin Boucher

You could nest div2inside div1:

你可以嵌套div2在里面div1

<div id="div1">
    <img src="\img1.png" />

    <div id="div2">
        <img src="\img1.png" />
    </div>

</div>