Centred flexbox items can have undesirable behaviour when they overflow their container.
Several non-flex solutions have been provided for this issue, but according to MDN there is a safe
value which is described as follows.
If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.
It can be used as follows.
align-items: safe center;
Unfortunately, I haven't been able to find any examples or discussions of this, or determine how much browser support there is for it.
I have attempted to use safe
in this CodePen. However, it doesn't work for me. The safe
seems to be ignored, or perhaps the container element is improperly styled.
I'd really appreciate it if anyone could shed some light on safe
and whether and how it can be used to solve the overflow problem, as demonstrated by the CodePen example.
To center the inner div element we will make the parent a flex container. By adding the display: flex; property we make the section element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center; .
It is definitely safe to use.
All you need to do is add both justify-content: center and align-items:center and flex-direction:column to the Header's CSS rules. You can use this combination of flexbox properties to center any element, not just navbars. Images, divs, etc can all be absolutely centered within a parent element.
In addition to the initial value of stretch, you can give align-items a value of flex-start , in which case they align to the start of the container and no longer stretch to the height. The value flex-end moves them to the end of the container on the cross axis. We can also do baseline alignment.
The safe
keyword is still a working draft, and not many (if any) browsers support it yet, so to get the same effect, cross browser, use auto margins for now, which should be set on the flex item.
Updated codepen
Note, to compensate for the modal
's 50px top/bottom margin, use padding
on modal-container
.
.modal-container
{
display: flex;
flex-direction: row;
justify-content: center;
align-items: flex-start; /* changed */
position: fixed;
width: 100vw;
height: 100vh;
overflow-y: scroll;
padding: 50px 0; /* added */
box-sizing: border-box; /* added */
}
.modal-container > #modal
{
display: flex;
flex-direction: column;
align-items: center;
margin: auto 0; /* changed */
padding: 12px;
width: 50%;
background-color: #333;
cursor: pointer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With