What is safe alignment in CSS?

Stefan Judis covered this recently, and like Stefan, I first heard of the safe keyword in CSS from Rachel Andrews at an AEA conference years ago. It’s used in addition to other alignment keywords in layout like this for example:

.flex {
  display: flex;
  align-items: safe center;
}
Code language: CSS (css)

The extra value safe here is essentially saying “don’t let the alignment force a situation where the content is positioned off the screen where a user can’t scroll to it”. Content that is pushed off the screen in a way a user can’t scroll to it (think off the top or left of a browser window, or any element with scrolling overflow) is called data loss. I love the term data loss in CSS because that’s exactly what it is. For sighted users who only access websites with their vision, if they can’t see content, it ain’t there.

Here’s my own demo for explaining this.

I’ll post a video here below. Without using the safe keyword, and using align-items: center; in a flexbox context, you can see how if there isn’t enough room in an element, it’s possible for elements to go up over the top (block start) of the element in such a way it’s impossible to scroll to. You can scroll down just not up.

Then if you add the safe keyword, you can see the the layout won’t let the items go up into that inaccessible/unscrollable. That way you can always scroll down to get the content, the content never goes up

See how the elements stick to the top as the size of the parent changes rather than go above it? safe!

Wanna learn modern CSS layout?

Leave a Reply

Your email address will not be published. Required fields are marked *

Did you know?

Frontend Masters Donates to open source projects. $363,806 contributed to date.