Div绝对定位高度不起作用

3
我正在尝试创建一个包含头部、主内容区和页脚的布局。 头部和页脚高度固定,但内容区需要填充宽度和高度(无滚动条)。 当前代码在这里
<div class="outer">
    <header>
        movistar ovacion
    </header>

    <div id="content" >

        <section class="step-1">
            
            <div class="box">
                <a href="#">HOMBRE</a>
            </div>
            <div class="box">
                <a href="#">MUJER</a>
            </div>
            <div class="box">
                <a href="#">NIÑO</a>
            </div>
            <div class="box">
                <a href="#">NIÑA</a>
            </div>

        </section>
    
    </div>

    <footer>
        footer
    </footer>
</div>

CSS:

html,body{
        height: 100%;
    }

    header {
        height: 160px;
        background: blue;
    }

    #content {
        
    }

    footer {
        height: 60px;
        position:absolute;
        width:100%;
        bottom:0; 
        background: green;
    }

.outer {
    
}
    .step-1 > div {
        width: 50%;
        height: 50%;
        position: absolute;     
    }

    .step-1 > div:first-child {
        background: #DDD;
        left: 0;
    }
    .step-1 > div:nth-child(2) {
        background: #CCC;
        right: 0;
    }
    .step-1 > div:nth-child(3) {
        background: #72CCA7;
        left: 0;
        bottom: 0;  
    }
    .step-1 > div:nth-child(4) {
        background: #10A296;
        right: 0;
        bottom: 0;
    }

现在内容区域无法正常工作,4个框不适应高度。

我认为我在div位置或清除方面做错了什么,但我找不到问题所在。

我该如何修复它?有更好的方法来完成这种布局吗?

2个回答

2
问题在于 .step-1 内的第一个和第二个 <div> 元素没有明确的 top 值。因此下一个绝对定位的 DIV 会重叠这两个元素:
.step-1 > div:first-child {
    background: #DDD;
    left: 0;
    top: 0;  /* Added declaration */
}

.step-1 > div:nth-child(2) {
    background: #CCC;
    right: 0;
    top: 0;  /* Added declaration */
}

另一方面,为了填补标题和页脚之间的剩余空间,#content 本身应该在这种情况下绝对定位:
#content {
    position: absolute;
    top: 160px;   /* = height of the header */
    bottom: 60px; /* = height of the footer */
    width: 100%;
}

演示效果

个人而言,我更喜欢为绝对定位的元素创建一个新的包含块,而不是依赖于初始包含块。因此,在上面的演示中,我将.outer元素定位为相对位置:

.outer {
    position: relative;
    height: 100%;
}

我该如何添加一个左侧边栏并使其与整个页面等高?是在 .outer div 外部浮动左侧边栏还是在 .outer div 内部添加? - Oterox
@Oterox 很抱歉回复晚了,你也可以通过这种方式实现 like this - Hashem Qolami

0

将右侧添加:0;似乎有所帮助

top: 100%;
left: 0;
right: 0;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接