【问题标题】:Position a dynamically sized div at the bottom of another dynamically sized div将动态大小的 div 放置在另一个动态大小的 div 的底部
【发布时间】:2021-12-10 09:40:06
【问题描述】:

我正在尝试创建一个将动态添加 LI 项的 UL。

目标是列表在空时高度为零,然后随着项目添加到列表中扩展至特定高度,并设置最大高度,以便如果列表增长超过特定高度,则所有较旧的项目被溢出隐藏:隐藏。

因此,位于列表底部的最新项目应始终可见,而较旧的项目会向上凸起并最终不可见。

我可以通过将 UL 包装在容器 DIV 中,为 div 设置固定高度,然后将 UL 设置为 position: absolute 并将容器 div 设置为 position 来获得大部分 : 相对的。

但是如果我为容器div设置了一个固定的高度,那么当列表没有项目时,列表上方和下方的界面项目之间仍然会有很大的空白。

为了不显得奇怪,我需要列表(及其容器 div)随着列表的增长动态调整高度,然后将增长限制在最大高度设置。

但是,如果我删除容器 div 的固定高度,它会将该 div 的高度设置为零像素,因为 UL 设置为 position: absolute,因此列表根本不会显示(作为整个list 被认为是在零高度 div 内溢出)。

这似乎是人们试图实现的相当普遍的事情,但我似乎找不到任何不涉及设置固定高度的解决方案。

代码示例...

HTML:

<div id="above_list">This should be touching the below_list div when the list is empty</div>
<div id="list_container">
    <ul>
        <li>Item 1
        <li>Item 2
        <li>Item 3
        <li>Item 4
        <li>Item 5
    </ul>
</div>
<div id="below_list">This should be touching the above_list div when the list is empty, and should get farther away from the above_list div as <li> items are added to the list

CSS:

#list_container {
    position: relative;
    max-height: 100px;
    overflow: hidden;
}

ul {
    position: absolute;
    bottom: 0;
}

在上面的代码示例中,即使列表有一堆列表项,容器 div 也会以零高度显示。

仅当列表没有项目时,我才需要容器 div 以零高度显示。然后容器 div 的高度应该随着项目添加到列表中而增长,并且如果列表超过某个高度,则应该停止增长。

列表需要定位在容器 div 的底部,这样如果列表开始溢出容器 div 的最大高度,而不是将较新的列表项隐藏在 div 的底部下方,它应该推送div 顶部上方的旧列表项。 (所以 UL 的顶部被视为溢出,而不是 UL 的底部被视为溢出。)

【问题讨论】:

  • 是的,您正在创建一个UL 并提供代码也帮助我们在这里创建:)
  • 添加了代码示例

标签: css list position bottom


【解决方案1】:

使用 flex 列并将内容对齐到 flex 端。

除非出于其他原因需要,否则根本不需要包装 div。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

ul {
  max-height: 150px;
  overflow: hidden;
  border: 1px solid grey;
  list-style: none;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
<div id="above_list">This should be touching the below_list div when the list is empty</div>
<div id="list_container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
  </ul>
</div>
<div id="below_list">This should be touching the above_list div when the list is empty, and should get farther away from the above_list div as items are added to the list
</div>

没有列表项的示例:https://codepen.io/Paulie-D/pen/vYJgPEY

【讨论】:

  • 这正是我想要的,谢谢!没有意识到 flexbox 可以像这样用于 UL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
相关资源
最近更新 更多