Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

html - How to center an element vertically in css in a scrollable container

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%);
}

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use flexbox with auto margins:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...