【问题标题】:How can I bottom align a div that can grow and cause it's container to scroll如何底部对齐可以增长并导致其容器滚动的 div
【发布时间】:2011-06-28 18:50:02
【问题描述】:

我正在尝试在没有 javascript 的情况下实现这种布局。

我有一个父 div 和一个子 div,其中包含不断附加的内容。我希望孩子在父母内部底部对齐并垂直成长。当孩子的高度>父母的高度时,我还希望父div滚动

第一部分很简单:

#child { position:absolute; bottom: 0 }

第二部分比较困难,因为绝对定位的元素在内容流之外,不会触发滚动。

父 div 跨越浏览器窗口的整个高度(我在设计时不知道)

【问题讨论】:

  • 你有没有机会把你的例子放在 jsfiddle 上?
  • 这是一个没有底部对齐的 JSFiddle:jsfiddle.net/epgdn/1 我试图在子元素较小时实现底部对齐,当它大于父元素时自动滚动。

标签: html css layout


【解决方案1】:

您将无法仅使用 CSS 来做到这一点。如果你将孩子定位在top:0,你会很好,因为页面是从上到下处理的(滚动条也是如此)。

body { font-size:1.2em; height:50%; color:#735005; }
div { margin:0; padding:0; }
#parent {
    border:1px solid red;
    height:100%; max-height:400px;
    overflow:auto;
    position:relative;
    width:300px;
    }
#child, #child2 {    /* #child2 is STRICTLY here to illustrate the desired effect */
    border:1px solid blue;
    position:absolute;
    bottom:0;
    }
#child2 { visibility:hidden; top:0; }

  <div id="parent">
     <div id="child">scroll scroll scroll ... scroll scroll scroll scroll</div>
     <div id="child2">scroll scroll scroll ... scroll scroll scroll scroll</div>
  </div>

显然,您不想为 UI 效果硬编码重复的代码。需要服务器/客户端脚本。

【讨论】:

    【解决方案2】:

    经过编辑表明这是可能的

    事实证明有可能提供所描述的动态布局不使用javascript。有一种方法(仅使用 CSS)使 div 底部对齐,当它溢出它的父级时会导致滚动。

    诀窍是让滚动发生在孩子身上,将其最大高度设置为 100%(即父母高度),然后将孩子底部与position:absolute; 对齐。你只需要确保父母有position:relative or absolute

    这是使它工作的简单 CSS:

    #parent{
        position:absolute;
        /* these parts are obviously not necessary */
        width:500px;
        top:10px;
        bottom:10px;
    }
    #child{
        position:absolute;
        bottom:0px;
        right:0px;
        left:0px;
        overflow-y:auto;
        /* this is the key */
        max-height:100%;
    }
    

    这反映在以下 jsfiddle 中:http://jsfiddle.net/epgdn/5/ 只需调整运行窗口的大小,直到子级大于父级并且父级将适当地滚动。

    【讨论】:

    • 即使内容小于容器,滚动条仍会显示。所以如果内容是父母高度的一半,就会有一半高度的垂直滚动条。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2021-10-25
    • 1970-01-01
    • 2018-01-29
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多