css - div位置绝对高度不起作用

标签 css html position

我正在尝试创建一个带有页眉、主要内容区域和页脚的布局。

页眉和页脚都是固定高度但内容区域需要填充宽度和高度(没有滚动条)

当前代码是here

<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 位置或清理方面做错了,但我找不到问题。

我该如何解决?有没有更好的方法来进行这种布局?

最佳答案

问题是第一个和第二个<div> .step-1 中的元素没有明确的 top值(value)。因此,下一个绝对定位的 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%;
}

WORKING DEMO .

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

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

关于css - div位置绝对高度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478580/

相关文章:

html - 如何通过调整浏览器窗口的大小来制作导航栏比例尺

html - 我如何获得一个绝对定位的 div 与溢出自动增长到其内容的宽度并将空白设置为 nowrap?

javascript - Jquery getOffset 函数返回未定义

html - 将绝对定位的 div 展开并定位到相对定位的父级

C# 如何在屏幕上的特定鼠标位置显示窗体?

html - 我无法下拉其父菜单下的子菜单

电子邮件模板中的 html 表格不会有 600px 的最大宽度,并且在 outlook 桌面或 outlook.com 中以页面为中心

html - 将图像居中放置在旋转 45 度的正方形上(或在菱形背景上)css

javascript - 需要在 html 表格中进行简单易用的分页

mongodb - 获取所选文档在集合中的位置 [mongoDB]