CSS: 水平滚动容器底部的粘性元素

CSS: Sticky element on the bottom of horizontally scrolling container

我正在尝试在水平滚动元素内制作粘性页脚。我希望该粘性页脚与底部对齐,根据其内容自动调整高度,并与滚动父级一样宽(在此示例中为 200 像素),因此当我向右滚动时,页脚位于同一位置并且是内容水平居中(内容应该是一些元素,而不仅仅是简单的文本)。我将不胜感激。

想要的解决方案:

我当前的代码:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

.example {
  width: 200px;
  overflow-x: auto;
}

.container {
  position: relative;
  display: flex;
  width: 400px;
  height: 100px;
  background-color: moccasin;
}

.footer {
  position: sticky;
  bottom: 0;
  background-color: palegreen;
  justify-self: center;
}
<div class="example">
  <div class="container">
    <div class="footer">
      Footer
    </div>
  </div>
</div>

非常感谢。

请查看以下更改。我更改了 .footer class 上的一些 CSS 以使其宽度为 100%,position: relative 然后我添加了 align-self: flex-end; 和一些滚动条样式使用 ::-webkit-scrollbar 随意更改它。

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

.example {
  width: 200px;
  overflow-x: auto;
}

.container {
  position: relative;
  display: flex;
  align-self: flex-end;
  width: 400px;
  height: 100px;
  background-color: moccasin;
}

.footer {
  position: relative;
  height: 20px;
  background-color: palegreen;
  align-self: flex-end;
  width: 100%;
  text-align: center;
}

::-webkit-scrollbar {
  width: 4px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: rgba(0, 0, 0, .5);
  box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}

p {
  margin: 0;
  padding: 0;
  position: fixed;
  margin-left: 5rem;
}
<div class="example">
  <div class="container">
    <div class="footer"><p>Footer</p></div>
  </div>
</div>

编辑: 您使用的是 justify-self: center;。使用 position: relative; 您可以使用 align-self: flex-end; 使页脚显示在底部。还添加了 position: fixed; 并留有一些边距,以便在滚动时保留文本。

希望这能解决您的问题: (添加了 Lorem Ipsum 以显示滚动效果和修复了页脚)

* {
  box-sizing: border-box;
  outline: 1px solid red;
}

body {
  margin: 0;
  padding: 0;
}

.example {
  width: 200px;
  height: 300px;
  overflow-x: auto;
}

.container {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 400px;
  height: 100%;
  background-color: moccasin;
}

.footer {
  position: sticky;
  width: 200px;
  height: 20px;
  top: 100%;
  background-color: palegreen;
  text-align: center;
  left: 0;
}
<div class="example">
  <div class="container">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum
    <div class="footer">
      Footer
    </div>
  </div>
</div>