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
533 views
in Technique[技术] by (71.8m points)

css - Issue when centering vertically with flexbox when heights are unknown

My layout has a container flex-container and a child.

HTML:

<div class="flex-container">
  <div>text</div>
</div>

The container and the child have an unknown height. And the goal is:

  • If the child has a lower height than the container, it appears centered horizontally and vertically.
  • If the child has a greater height than the container, it adjusts to the top and the bottom and we can do scroll.

Scheme: enter image description here

The fastest way for centering a element with flexbox is the follow:

.flex-container
{
  display: flex;
  align-items: center; /* vertical */
  justify-content: center; /* horizontal */

  width: 100%;
  height: 300px; /* for example purposes */
  overflow-y: scroll;
  background: #2a4;
}

.flex-container > div
{
  background: #E77E23;
  width: 400px;
}
<div class="flex-container">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I found the solution:

.flex-container {
    display: flex; /* only */
    overflow-y: scroll;
}

.flex-container > div {
    margin: auto; /* horizontal and vertical align */
}

html, body {
    height: 100%;
    width: 100%;
    padding: 0;
    margin: 0;
}

.flex-container {
    display: flex;
    width: 100%;
    height: 100px; /* change height to 300px */
    overflow-y: scroll;
    background: #2a4;
}

.flex-container > div {
    padding: 1em 1.5em;
    margin: auto;
    background: #E77E23;
    width: 400px;
}
<div class="flex-container">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>
</div>

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

...