7

我的 HTML 中有一些 div,其中一个正在加载图像 div,所以我希望它与其父 div 重叠。这是我的代码:

<div id="something1">
    <div id="something2"></div>
    <div id="parent" style="border: 15px solid #c1c1c1;width:200px; height:250px;">
        <div id="child" style="position: absolute; border: 15px solid #a2f2e2"></div>
    </div>
</div>

当我使用不同的位置(即绝对、相对等)时,子 div 不能与其父级重叠。这是我的小提琴链接: http: //jsfiddle.net/yNFxj/4/我不想从父 div 看到任何东西,但我想看到子 div 随着父级的大小而增加并重叠。

关于如何仅使用纯 html 和 css 以及使用通用方式在任何其他页面上实现它的任何想法?

PS:边框、宽度、高度等只是举例,可以去掉。

4

5 回答 5

18

据我所知,Sajjan 是最接近的,但他有一些缺陷:

  1. Position: absolute要求其父级具有非静态位置(这通常使用 来完成position: relative,它的工作方式与静态相同)。
  2. 您不需要设置孩子的高度和宽度,只需设置父母。

这是我的小提琴来演示。

#parent {
    border: 5px solid gray;
    position: relative;
    height: 100px;
    width: 100px;
    margin-left: 50px;
}

#child {
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    background: red;
}

这里的关键是position: relative父级。

不过,我很好奇,你到底想用这个实现什么。我有一种感觉,不管它是什么,都有更好的方法。

于 2013-01-30T14:36:22.463 回答
1

为什么这对你不起作用?如果我理解正确,您只想用子 DIV 掩盖父 DIV?

<div id="something1">
  <div id="something2"></div>
  <div id="parent" style="border: 15px solid #c1c1c1;width:200px; height:250px;">
    <div id="child" style="position: absolute; border: 15px solid #a2f2e2;top:0;left:0;width:200px; height:250px;"></div>
  </div>
</div>

铬上的输出: 在此处输入图像描述

为了使其通用,使用 offsetTop/Left/Height/Width 方法获取父母的位置/尺寸,并使用这些方法设置孩子的尺寸/位置,我确信在 SO 上有很多帖子可以做到这一点..

于 2013-01-30T13:56:42.997 回答
1

第一个问题是absolute定位元素是指位置不同的第一个父元素static

这意味着如果没有父母有fixed, relative, 或absolute位置,它将引用身体,在这种情况下,这不是你想要的。

然后放到position: relative;你的父 div 中。

第二个问题:使用绝对位置,你可以停止使用widthandheight并开始使用top, left, bottomandright属性;

将它们全部设置为0意味着将对象扩展到父边界

但是在这里你想重叠它们,然后......简单地,使用一个负值等于父边框的大小:15px;

top:    -15px;
left:   -15px;    
bottom: -15px;    
right:  -15px;

演示:http: //jsfiddle.net/yNFxj/9/

我使用了虚线边框,因此您可以看到父级边框的下方;)

于 2013-01-30T14:12:48.943 回答
0

HTML

<div id="something1">
<div id="something2"></div>
<div id="parent">
    <div id="child"></div>
</div>
</div>

CSS

#parent { 
  width: 100px;
  height: 300px;
  background-color: #a0a0a0;
  width:200px;
  height:250px;
  position: relative;
}

#child {
  width: inherit;
  height: inherit;
  position: absolute;
  background-color: #a2f2e2;
  top: 0px;
  left: 0px;
}

工作正常

编辑:为您添加和高度继承并正确定位

于 2013-01-30T13:59:16.633 回答
0

试试这个:

<div id="something1">
<div id="something2"></div>
<div id="parent" style="border: 15px solid #c1c1c1;position:relative; width:200px; height:250px;">
    <div id="child" style="position: absolute; border: 15px solid #a2f2e2; width:200px; height:250px; left:-15px; top:-15px"></div>
</div>
</div>

为您更新小提琴http://jsfiddle.net/yNFxj/16/

于 2013-01-31T05:14:16.180 回答