Better 'safe' than sorry

Did you know that one of the goals with CSS is to prevent data loss? The goal of CSS is to keep content and elements visible to the user and does this by design, most of the time.

CSS makes containers expand automatically to the right or the bottom depending on their content. They also become scrollable automatically when contents are overflowing. Unless you break the CSS default behavior with things like ‘overflow: hidden’, the user will always be able to access the content.

But. You knew it would come a but, didn’t you? When you use Flexbox, there are some situations where this default behavior won’t work as expected.

Consider this markup:

  <span>Good Vibes</span>

With this css:

div {
  display: flex;
  flex-direction: column;
  align-items: center;

How can this go wrong?

What will happen when the container shrinks and becomes really narrow? It will actually cut off words both on the left and the right side. So don’t we still have that possibility to scroll that we talked about earlier? Yes, we will but it will only scroll to the right, resulting in that the first letters of ‘Good Vibes’ being cut off and the visibility of the data to the user is lost.

‘safe’ to the rescue! If you look att the exemple below you see that we have a new word before ‘center’ that does all the magic and will fix this right away.

div {
  display: flex;
  flex-direction: column;
  align-items: safe center;

How does ‘safe’ work?

If you use ‘safe’, the aligning elements will switch to ‘start’ alignment in case of an overflowing situation. In this case it means that all the flexbox children will align to the left side and then we can scroll to the right to see the rest. Nice right?

As of right now this is supported by the chromium browsers and Firefox. But use it! Although Safari doesn’t support it yet, Safari will simply ignore the ‘safe’ keyword and get the default behaviour. The browser support will expand soon. It is already in Safari Technology Preview.

I really like this little tool!