如何在css中将元素垂直放在可滚动容器中

问题描述:

我尝试使用css在父元素内垂直居中元素。父元素具有动态高度,如果父元素的高度小于子元素的高度,我想父元素框滚动。我尝试使用弹性框和transform:translate技巧描述这里( https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/ )中心的孩子。两种技术都可以工作,但是当父级太小时会导致奇怪的滚动行为。

I am trying to center an element vertically inside a parent element using css. The parent element has a dynamic height and I would like the parent box to scroll if the height of the parent is less than the height of the child. I tried using flex boxes and the transform: translate technique described here (https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/) to center the child. Both techniques worked, but resulted in strange scrolling behavior when the parent gets too small.

#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/

Here is a jsfiddle that shows what I mean: http://jsfiddle.net/snhpdL91/

请注意,如果您缩放窗口向下,直到滚动条出现文本hello在孩子的顶部被切断,即使滚动到最顶部。

Notice that if you scale the window down until the scroll bars appear the text "hello" at the top of the child is cut off, even when scrolled to the very top. How can I make it so that I can scroll across the full range of the child element?

你可以使用flexbox with auto marginins :

You can use flexbox with auto margins:


在通过 justify-content align-self

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

这是有效的,因为只有空间是分布式的。

It works because only positive free space is distributed.

#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>