如何在css中将元素垂直放在可滚动容器中 [英] How to center an element vertically in css in a scrollable container

查看:128
本文介绍了如何在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 < a href =http://www.w3.org/TR/css-flexbox-1/#auto-margins =nofollow> auto marginins < a>:

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>

这篇关于如何在css中将元素垂直放在可滚动容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆