css - 试图让一个 div 相对或绝对定位在另外两个之上

标签 css css-position

HTML:

<div id="outer1">
    <div class="bg">
        <div class="top"></div>  
        <div class="base"></div>  
    </div>  
    <div class="content"></div>
</div>
<div id="outer2">
    <div id="bg">
        <div class="top"></div>  
        <div class="base"></div>  
    </div>  
    <div class="content"></div>
</div>

CSS2:

div { width: 100%; }

#outer1, #outer2 {position: relative;}
#outer1 .top { height: 200px; background-color: blue; } 
#outer1 .base { height: 200px; background-color: yellow; } 

#outer2 .top { height: 200px; background-color: green; } 
#outer2 .base { height: 200px; background-color: yellow; } 

.content { 
    width: 160px; margin: 0 auto;
    position: relative; bottom: 250px; height: 300px; background-color: white; border: 1px solid black;}

This is the fiddle

白色、黑色边框的 div (.content) 应该位于分色背景 (.bg) 上(按原样)。

使用相对定位 - 但我告诉它向上移动 (250px) 的空间仍然被它的父级占用 (#outer1)。 (两个“外部”div 之间有一个间隙 - 它们应该接触)

我尝试了绝对定位,但由于内容 div 比相对内容高,所以高度不符合要求。因为它是动态内容,所以我不能给它一个固定的高度(尽管我这样做是为了说明)

一个选项是 javascript,另一个是在上半部分使用背景中继器。

纯CSS2可以实现吗?

最佳答案

编辑:完成重写...

这是新的 fiddle :http://jsfiddle.net/FSXj8/14/

好吧,我冒昧地从头开始。这是 html

<div id="outer1" class="container">
    <div class="content">
        <div class="innerContent">hello world</div>
    </div>
    <div class="top"></div>
    <div class="base"></div>
</div>
<div id="outer2" class="container">
    <div class="content">
        <div class="innerContent">hello world</div>
    </div>
    <div class="top"></div>
    <div class="base"></div>
</div>

这是CSS

div {
    width: 100%;
}
.container {
    height: 400px;
    display: table;
    position: relative;
}
.top, .base {
    position: absolute;
    left: 0;
    height: 50%;
    z-index: 0;
}
.top {
    top: 0;
}
.base {
    bottom: 0;
}
#outer1 .top {
    background-color: blue;
}
#outer1 .base {
    background-color: yellow;
}
#outer2 .top {
    height: 50%;
    background-color: green;
}
#outer2 .base {
    height: 50%;
    background-color: yellow;
}
.innerContent {
    min-height: 100px;
    border: 1px solid black;
    background-color: white;
    width: 100px;
}
.content {
    display: table-cell;
    position: relative;
    vertical-align: middle;
    z-index: 1;
    background-color: transparent;
    height: 100%;
}

关于css - 试图让一个 div 相对或绝对定位在另外两个之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556759/

相关文章:

javascript - 无法重置 svg 路径的填充颜色?

javascript - 无法从 Imgur 相册创建随机播放的 Gif 幻灯片

css - 上传到服务器时不显示div

css - 响应式设计中的固定位置

css - 在响应式布局中绝对定位背景

php - Bootstrap CSS 会覆盖主题吗?

html - 左浮动侧边栏 css- 使用 jquery 进行滚动事件

html - 水平DIV图像容器

css - 为什么位置: relative use top to shift down and bottom to shift up?

html - 如何防止绝对定位的元素影响滚动条?