【问题标题】:div position absolute height not workingdiv位置绝对高度不起作用
【发布时间】:2021-02-28 11:19:46
【问题描述】:

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

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

当前代码是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 位置或清除方面做错了,但我找不到问题。

我该如何解决?有没有更好的方法来做这个布局?

【问题讨论】:

    标签: css html position


    【解决方案1】:

    问题在于.step-1 中的第一个和第二个&lt;div&gt; 元素没有明确的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%;
    }
    

    WORKING DEMO

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

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

    【讨论】:

    • 我怎样才能添加一个左侧边栏全高呢?在 .outer div 外部并在外部 div 左侧或内部浮动?
    • @Oterox 很抱歉回复晚了,您也可以实现like this
    【解决方案2】:

    添加权:0;似乎有帮助

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-29
      • 2011-04-19
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多