html - 如何在可滚动容器的CSS中垂直居中元素

标签 html css

我正在尝试使用 css 将元素在父元素内垂直居中。父元素具有动态高度,如果父元素的高度小于子元素的高度,我希望父元素框滚动。我尝试使用 flex boxes 和这里描述的 transform: translate 技术 ( https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/ ) 来使 child 居中。这两种技术都有效,但当父项太小时会导致奇怪的滚动行为。

#wrapper {
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: auto;
position: absolute;
}

.center {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}

这里有一个 jsfiddle 说明了我的意思:http://jsfiddle.net/snhpdL91/

请注意,如果您缩小窗口直到出现滚动条,即使滚动到最顶部,子项顶部的文本“hello”也会被截断。我怎样才能让它滚动到子元素的整个范围?

最佳答案

您可以将 flexbox 与 auto margins 一起使用:

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

之所以有效,是因为只分配了可用空间。

#wrapper {
  display: flex;
}
.center {
  margin: auto;
}

#wrapper {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
  position: absolute;
  display: flex;
}
.center {
  width: 300px;
  height: 300px;
  background-color: yellow;
  margin: auto;
}
<div id="wrapper">
  <div class="center">Hello</div>
</div>

关于html - 如何在可滚动容器的CSS中垂直居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31215600/

相关文章:

css - 将自定义类添加到 react 虚拟化网格

html - 在 Bootstrap 中使用 Div 在图像上显示文本

javascript - 将网页表单数据传递到我所在计算机上的 Python 脚本

html - 覆盖父溢出 - 选择

html - 防止渲染阻塞 CSS

javascript - safari&IE中链接形状坐标浏览器

html - 加载掩码,禁用底层 html 元素

css - 位置:Chrome 与 Safari 中的粘性

javascript - 显示折叠标题的重置/显示按钮

不在文件夹之间使用斜杠的 URL 的 JavaScript 面包屑