The problem here is caused by the fact that when using align-items
(or justify-content
) to center a flex row item, it will, by design, overflow at its top/bottom (or left/right).
To solve that a new keyword, safe
, is introduced, though not many browsers support it yet.
The other option is to use auto margin's, though with the given markup you can't, as the text doesn't have an inner wrapper (well, it has an anonymous one, though those we can't target with a CSS selector).
So by adding an inner wrapper (fiddle with wrapper) you can use auto margin's, and is well explained here:
But sometimes we just can't change the markup, and when, here is a little trick, using the pseudo elements, and use auto margin's on them.
To vertical center the text we also need the flex direction to be column
so the pseudo is rendered above/below.
Stack snippet
div {
display: flex;
flex-direction: column; /* added */
width: 100px;
height: 50px;
overflow: auto;
word-break: break-word;
border: 1px solid gray;
}
div::before, div::after {
content: '';
}
div::before {
margin-top: auto; /* added */
}
div::after {
margin-bottom: auto; /* added */
}
<div>
sdjhfkahsdkjfadsfhk jaskjfsj fsldflkasjklsjflakj flksjfakljflksjflkasfjklasjflfd
</div>
<div>
sdjhf
</div>