I recently watched the talk Making Things Better: Redefining the Technical Possibilities of CSS by Rachel Andrews. Rachel's talks are always full of useful information presented clearly and compactly. The talk included one line of CSS that I haven't seen before.
// 👇 what is that? 😲
align-items: safe center;
Rachel explains that when the CSS specs are written, one of the key priorities is to prevent data loss. I heard this phrase for the first time. How often do we face data loss in CSS and what is done to prevent it?
The goal of CSS is to keep content and elements visible to the visitor. CSS does that by design. Containers expand automatically to the right or the bottom depending on their content. They become scrollable when contents are overflowing. Unless you disable this behavior with an
overflow: hidden; on an element, the user will be able to access the content.
I learned that when you use Flexbox there are situations in which the prevention of data loss is not guaranteed.
Let's say you have the following HTML:
paired with the following CSS:
The align-items property aligns child element centered along the cross axis. This is all great, but in case of a small container/viewport size we end up with a situation of data loss.
Due to the flexbox alignment, the elements are centered no matter what. The child element overflow on the right and left side. The problem is that the overflowing area on the left side is past the viewport’s start edge. You can not scroll to this area – say hello to data loss.
This situation is where the
safe keyword of the
align-items property can help. The CSS Box Alignment Module Level 3 (still in draft state) defines safe alignment as follows:
"Safe" alignment changes the alignment mode in overflow situations in an attempt to avoid data loss.
If you define
safe alignment, the aligning elements will switch to
start alignment in case of an overflowing situation.
align-items: safe center;
safe alignment leads the browser to always place elements accessible to the user.
With only Firefox supporting the
safe keyword cross-browser support is not given. I wouldn't recommend using it today because it is not falling back nicely. One could argue that the safe way should be the
align-items default, but what can I say, CSS is hard. Writing CSS specs is even more complicated. 🤷🏻♂️
How can you prevent data loss today, though?
Bramus Van Damme pointed out that a
margin: auto; on the flex children does the job even without the
safe keyword. 🎉
It never appeared to me that centered alignment could cause data loss. The described example shows how complex CSS specs and layout are. The people working on specs have my most profound respect!
And that's it for today, let's see when safe alignment makes it into cross-browser support. 👋🏻