2014-04-09 42 views
0

我在如何构建正在处理的新小部件时遇到了一些问题。我试图实施一个包含一些热点的地理地图,就像老式的图像地图一样。但是,出于各种目的,我想在不使用图像映射的情况下完成它。在调整容器内堆叠div元素

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

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索引divs。它们从布局的其余部分分离,导致父容器不能展开,从而将后续元素放置在绝对定位的元素下面。

我正在寻找关于如何在彼此顶部堆叠两个div(较低和较高容器)并将父容器展开为较低div大小的想法。

+0

只是想知道,是什么让你不选择我的答案,这基本上是相同的,但来得早? – Sunyatasattva

+0

我投了两个答案。除了一个解决方案,rgthrees答案还包含一个代码示例和一个jsfiddle链接,它演示了一个工作实现。 –

+0

我的解决方案还包含一个指向jsfiddle的链接,演示了实现,并描述了代码中所需的更改以使其可用。无论如何,永远不会:) – Sunyatasattva

回答

1

你真的只需要你的一个孩子要绝对定位:即放置在顶部(.higher-container)之一。这样,.lower将始终高于.higher-container将正常拉伸父容器,然后higher-container将层,排在顶层。我们只需要一个topleft定位添加到它:

这里有一个的jsfiddle:http://jsfiddle.net/rgthree/M6jm8/

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

.higher-container { 
    position: absolute; 
    top:0px; 
    left:0px; 
    z-index:1; 
    background-color: rgba(255,0,0, 0.3); 
} 
3

我不确定你为什么在.lower容器上使用position: absolute。将其用作relative,然后将top: 0规则指定给.higher-container

Updated fiddle