I want to make a simple popup with variable height which will vertically centered in case it is smaller than viewport and will not be shrinked when it bigger than viewport. Here is sample code:
.flex-container { height: 100%; display: flex; flex-direction: column; justify-content: center; } .flex-child { flex-shrink: 0; } .item { height: 160px; background-color: #C3C3FC; border: 1px solid red; }
<div class="flex-container"> <div class="flex-child"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div>
Note that height: 100%
on the flex container is ignored because its containing block ( body
) has height: auto
.
Therefore, the height of the flex container will be the height of its content, so justify-content: center
won't be noticeable.
To fix it, you can add a fixed height to body
:
html, body {
height: 100%;
margin: 0;
}
But then, if the content is taller than the viewport, the result will be undesirable, because since you have justify-content: center
, the content will overflow both from above and below, but the scrollbar won't allow to see the above overflow.
So you shouldn't use a fixed height for the flex container, you only need a minimum height, so that it will be allowed to grow if necessary:
.flex-container {
min-height: 100%;
height: auto; /* Initial value */
}
html, body { height: 100%; margin: 0; } .flex-container { min-height: 100%; display: flex; flex-direction: column; justify-content: center; } .flex-child { flex-shrink: 0; } .item { height: 160px; background-color: #C3C3FC; border: 1px solid red; }
<div class="flex-container"> <div class="flex-child"> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> <div class="item"> </div> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.