在调整容器内堆叠div元素

时间:2014-04-09 17:52:17

标签: html css html5

我在如何构建我正在处理的新小部件方面遇到了一些麻烦。我正在尝试实现一个包含一些热点的地理地图,就像旧学校的图像地图一样。但是,出于各种目的,我想在不使用图像映射的情况下完成它。

到目前为止,我已经得到了这个不完整的解决方案:

http://jsfiddle.net/nielsbuus/FZJ8E/1/

HTML:

<div class="parent">
    <!-- I'm a container, I need to expand in height, when my children expand, so they don't overlap elements beneath me. Sort of like clearing floats -->
    <div class="lower">
        <!-- I contain an image. My width is fixed, but my height may vary. -->
        <img src="http://placekitten.com/300/325" />
    </div>
    <div class="higher-container">
        <div style="top: 20px; left: 30px" class="higher-spot">foo</div>
        <div style="top: 80px; left: 50px" class="higher-spot">bar</div>
        <div style="top: 85px; left: 70px" class="higher-spot">baz</div>
    </div>
</div>
<div class="successor">
  Please keep me below all of this.
</div>

CSS:

.parent {
    background-color: #ccffff;
    padding: 20px;
    position: relative;
}

.lower {
    position: absolute;
    width: 300px;
    background-color: rgba(0,0,0,0.2);
    z-index: 0;
}

.higher-container {
    position: absolute;    
    background-color: rgba(255,0,0, 0.3);
}

.higher-spot {
    position: absolute;
    width: 25px;
    height: 25px;
    background-color: rgba(0, 255, 0, 0.5);
    z-index: 1px;
}

.successor {
    font-size: 18px;
    font-family: sans-serif;
}

这里的主要问题是使用绝对定位的z-indexed div。它们与布局的其余部分分离,导致父容器不展开,从而将后续元素放置在绝对定位的元素下面。

我正在寻找关于如何将两个div(较低和较高容器)堆叠在一起并让父容器扩展到较低div的大小的想法。

2 个答案:

答案 0 :(得分:3)

我不确定您在position: absolute容器上使用.lower的原因。将其用作relative,然后为top: 0提供.higher-container规则。

Updated fiddle

答案 1 :(得分:1)

你真的只需要一个孩子绝对定位:放在顶部的孩子(.higher-container)。这样,始终高于.lower的{​​{1}}将正常拉伸父容器,然后.higher-container将是层,而不是顶层。我们只需要为其添加higher-containertop定位:

这是一个jsfiddle:http://jsfiddle.net/rgthree/M6jm8/

left
相关问题