Html 元素高度与其他元素高度相同,但更宽且绝对定位

Html 元素高度与其他元素高度相同,但更宽且绝对定位,html,css,Html,Css,这是一个 下面的代码将div作为背景的一部分。如果用户的屏幕分辨率为1024px,则不会显示滚动 问题是我需要背景div与内容的高度相同 有没有办法只使用css来实现这一点 <body> <style> body { margin:0px; background: yellow; } #background { overflow: hidden;

这是一个

下面的代码将div作为背景的一部分。如果用户的屏幕分辨率为1024px,则不会显示滚动

问题是我需要背景div与内容的高度相同

有没有办法只使用css来实现这一点

<body>
    <style>
        body {
          margin:0px;
          background: yellow; 
        }
        #background { 
            overflow: hidden; 
            position: absolute; 
            z-index: -1;
            width: 100%; 
            height: 100%; /* ??? */
        }
        #background > div { 
         background: blue;
            margin: auto;
            width: 1108px;
            height: 100%;
            z-index: -1;
        }
        #content {
            background: red;
            width: 1004px;
            margin: auto;
        }
    </style>
    <div id="background"><div><!-- this will not affect page scrolling if its width id greater than browsers window --></div></div>
    <div id="content">
        lorem ipsum dolor sit amet<br />
            [...]
    </div>
</body>

身体{
边际:0px;
背景:黄色;
}
#背景{
溢出:隐藏;
位置:绝对位置;
z指数:-1;
宽度:100%;
高度:100%;/**/
}
#背景>div{
背景:蓝色;
保证金:自动;
宽度:1108px;
身高:100%;
z指数:-1;
}
#内容{
背景:红色;
宽度:1004px;
保证金:自动;
}
lorem ipsum dolor sit amet
[...]


编辑:

谢谢你的否决票和评论。我自己找到了答案。您只需用



EDIT2:


或者只给
位置:relative

引用OP:问题是我需要#背景div与#内容的高度相同

如果你想让#background始终与#content保持相同的高度,只需将#content div放入#background div.

好的,我引入了
id=“parent”
div,然后我添加了
top:0
bottom:0
hack to
#background
div来将高度调整为
parent
div

我还更改了示例小提琴的宽度,因此可以看到它正在工作:

<body>
    <style>
    body {
        margin:0px;
        background: yellow;
    }
    #parent{
        position:relative;
    }
    #background {
        background-color:black;
        overflow: hidden;
        position: absolute; 
        z-index: -1;
        top:0;
        bottom:0;
    }
    #background > div {
        margin: auto;
        width: 1108px;
        height: 100%;
    }
    #content {
        background: red;
        width: 1004px;
        margin: auto;
    }
    </style>
    <div id="parent">
        <div id="background">
            <div><!-- this will not affect page scrolling if its width id greater than browsers window -->
            </div>
        </div>
        <div id="content">
            lorem ipsum dolor sit amet<br />
            [...]
        </div>
    </div>
</body>

身体{
边际:0px;
背景:黄色;
}
#母公司{
位置:相对位置;
}
#背景{
背景色:黑色;
溢出:隐藏;
位置:绝对位置;
z指数:-1;
排名:0;
底部:0;
}
#背景>分区{
保证金:自动;
宽度:1108px;
身高:100%;
}
#内容{
背景:红色;
宽度:1004px;
保证金:自动;
}
lorem ipsum dolor sit amet
[...]

这就是你想要的吗?

对不起。不,我不能接受。我先弄明白了。你不需要底部:0;排名:0;让它工作起来。@seler对不起,seler,但是你需要在代码上加上这个技巧,否则,当你在
#background
中加上更多的代码时,它的高度会增加!(先测试解决方案!!)@Nacho抱歉,Nacho我不需要
#background
中的任何内容,这就是为什么它被命名为background。我测试了你的解决方案。添加top:0;底部:0;改变不了什么。@seler我仍然对让你的知识增长感到满意。。。如果你将来需要这个黑客,你知道它是如何工作的。@Nacho它在FF、Chrome、Opera中工作,没有top:0;底部:0;