P粉8462943032023-08-23 09:16:51
I only used 3 containers to achieve this effect. The trick is to separate the flexbox container from the container that controls the scrolling. Finally, put everything into a root container to center it. Here are the key styles needed to create the effect:
.root { display: flex; justify-content: center; align-items: center; } .scroll-container { margin: auto; max-height: 100%; overflow: auto; } .flex-container { display: flex; flex-direction: column; justify-content: center; }
<div class="root"> <div class="scroll-container"> <div class="flex-container"> <p>Lorem ipsum dolor sit amet.</p> </div> </div> </div>
I created a demo here: https://jsfiddle.net/r5jxtgba/14/
P粉6708387352023-08-23 00:51:49
Flexbox makes centering very easy.
Just apply align-items: center
and justify-content: center
to the flex container and your flex items will be centered vertically and horizontally.
However, there is a problem with this approach when the flex items are larger than the flex container.
As pointed out in the question, when flex items overflow the container, the top becomes inaccessible.
For horizontal overflow, the left part becomes inaccessible (or the right part in RTL languages).
Here is an example of a LTR container with justify-content: center
and three flex items:
See the bottom of this answer for a description of this behavior.
To resolve this issue, use flexbox auto-margins instead of justify-content
.
Using auto
margins, overflowed flex items can be centered vertically and horizontally without losing access to any part of them.
So, don’t use this code on a flex container:
#flex-container { align-items: center; justify-content: center; }
Use this code on the flex item:
.flex-item { margin: auto; }
Add the safe
value to your keyword alignment rules as follows:
justify-content: safe center
or
align-self: safe center
From CSS Box Alignment Module Specification:
Note: The Box Alignment module works with multiple box layout models, not just flex. So, in the specification excerpt above, the terms in square brackets are actually "alignment body", "alignment container", and "start
". I'm using flex-specific terms to keep the focus on this particular issue.