CSS

`font-display`, a CSS alternative to JavaScript font loading

The font-display property is landing in browsers, and this is a great introduction to using it:

If you don’t know which option to use, then go with swap. Not only does it provide an optimal balance between custom fonts and accessibility of content, it provides the same font loading behavior that we’ve relied on JavaScript for. If you have fonts on the page that you’d like to have load, but could ultimately do without, consider going with fallback or optional when using font-display.

Until it’s more widely supported, you can continue to use a JavaScript solution, but even then you can feature detect first:

Code language: JavaScript

if ("fontDisplay" in document.body.style === false) {
  /* JavaScript font loading logic goes here. */
}

Multi-line Padded Text with the CSS box-decoration-break Property

I love stumbling upon CSS properties in time of great need. Recently, I was working on a personal project, and I wanted to have multi-line highlighted text. My requirements were pretty simple from a design point of view:

  1. Text should be highlighted, i.e. have a background colour
  2. Highlights should only cover areas where there is text
  3. Each line should have a little left and right padding so that the text isn’t flush against the highlight box

My desired HTML was something like this:

Code language: HTML

<span>Hello, this is a long string of text that spills onto many lines</span>

And the desired output something like this:

If I used it as is, the output would look something like this:

So, how can we solve this? Luckily, CSS has thrown us a piece of candy in the box-decoration-break property. Let’s take a look.

[…]

Here’s an excerpt from the MDN:

The box-decoration-break CSS property specifies how the background, padding, border, border-image, box-shadow, margin and clip of an element is applied when the box for the element is fragmented. Fragmentation occurs when an inline box wraps onto multiple lines…

Basically, this property is giving us a bit more granularity in how an inline element gets rendered. By default, it’s set to slice, which means that it treats the inline box as if it weren’t fragmented at all. I like to think of it like this. Imagine that we took that multi-line inline element, stretched it out onto one line, applied the styling, sliced it into pieces, then moved each piece back to a new line. The result would be that the properties mentioned above would act on the entire box of the element, rather than each of its parts.

However, there is a second option for us, and that is:

Code language: CSS

box-decoration-break: clone;

When we set the property to clone, we can imagine a similar scenario as above, except one important thing. This time, let’s imagine that all the styles get applied after the element gets fragmented and distributed on multiple lines. In other words, paddings, borders, etc would be applied to each fragment almost as if they were separate elements.

That’s pretty awesome, and with one simple property, we’ve unleashed a ton of possibilities! Here’s a CodePen link with various demos for you to play around with.

In the detail: close button (or how to style a close button using a font for the icon)

There’s a × character in most common fonts which you should use instead of an x for close, but getting it to look right across devices requires an eye for the detail.

Here’s a screenshot of the simulator vs. the real device, with exactly the same CSS applied to create the effect. Notice that the vertical align is off?

It took me a while to work out what was different, but it’s the font. The font I’m using (if you’re on a Mac - as I was), is Helvetia Neue, but my Android doesn’t have that font, so it was falling back to the next default (possibly set as sans-serif, which could be Open Sans, or it could be something else). In this case, the different font had a slightly different letter height, so it caused (obviously) as slightly different result.

The pro tip: make sure to use a common font, probably Arial (IHMO ideally a font that doesn’t need to be downloaded) for button icons.

Yes, I know this is obvious if you’re using an icon font…but maybe not immediately obvious if you’re re-using system fonts.

CSS Writing Modes

You can use a little-known, yet important and powerful CSS property to make text run vertically.

Or instead of running text vertically, you can layout a set of icons or interface buttons in this way. Or, of course, with anything on your page.

[…]

If you do want a bit more of a taste, look at this example that adds text-orientation: upright; to the mix — turning the individual letters of the latin font to be upright instead of sideways.

Code language: CSS

h1 {
  writing-mode: vertical-rl;
  text-orientation: upright;
  text-transform: uppercase;
  letter-spacing: -25px;
}

GPU Animation: Doing It Right

Most people now know that modern web browsers use the GPU to render parts of web pages, especially ones with animation. For example, a CSS animation using the transform property looks much smoother than one using the left and top properties. But if you ask, “How do I get smooth animation from the GPU?” in most cases, you’ll hear something like, “Use transform: translateZ(0) or will-change: transform.”

These properties have become something like how we used zoom: 1 for Internet Explorer 6 (if you catch my drift) in terms of preparing animation for the GPU — or compositing, as browser vendors like to call it.

But sometimes animation that is nice and smooth in a simple demo runs very slowly on a real website, introduces visual artefacts or even crashes the browser. Why does this happen? How do we fix it?

[…]

  • Watch out for the number and size of composite layers from the very beginning — especially ones created by implicit compositing. The “Layers” panel in your browser’s development tools is your best friend.
  • Modern browsers make heavy use of compositing not just for animation but to optimize the painting of page elements. For example, position: fixed and the iframe and video elements use compositing.
  • The size of compositing layers is likely be more important than the number of layers. In some cases, the browser will try to reduce the number of composite layers (see the “Layer Squashing” section of “GPU Accelerated Compositing in Chrome“); this prevents so-called “layer explosion” and reduces memory consumption, especially when layers have large intersections. But sometimes, such optimization has a negative impact, such as when a very large texture consumes much more memory than a few small layers. To bypass this optimization, I add a small, unique translateZ() value to each element, such as translateZ(0.0001px), translateZ(0.0002px), etc. The browser will determine that the elements lie on different planes in the 3D space and, thus, skip optimization.
  • You can’t just add transform: translateZ(0) or will-change: transform to any random element to virtually improve animation performance or to get rid of visual artifacts. GPU compositing has many drawbacks and tradeoffs to be considered. When not used sparingly, compositing will decrease overall performance at best, and crash browsers at worst.

Allow me to remind you of the big disclaimer: There is no official specification for GPU compositing, and each browser solves the same problems differently. Some sections of this article may become obsolete in a few months.

CSS Shorthand Syntax Considered an Anti-Pattern

Typically we would view shorthand syntax as a benefit: fewer keystrokes, fewer lines of code, less data over the wire. Sounds great! However, it comes with a rather troublesome side effect: it often unsets other properties that we never intended to modify.

When we write something like:

Code language: CSS

.btn {
  background: red;
}

…we’re likely to get a red background colour applied to our button. But what we’re really saying is this:

Code language: CSS

.btn {
  background-image: initial;
  background-position-x: initial;
  background-position-y: initial;
  background-size: initial;
  background-repeat-x: initial;
  background-repeat-y: initial;
  background-attachment: initial;
  background-origin: initial;
  background-clip: initial;
  background-color: red;
}

Simply by using the shorter syntax, we have implicitly decided that we want no image to start top-left, repeat x and y, to scroll with the element, and so on…

Nearly every problem, bug, or regression in CSS at scale is happens because we did too much too soon, and further down the line we’re being affected by that. What this basically comes down to is the fact that, with CSS, you should only ever do as little as you need to do and nothing more.

Misusing shorthand syntax is a surefire way to do too much too soon, as thus it should be avoided. CSS is a lot harder to undo than it is to do.

Performant Parallaxing

Love it or hate it, parallaxing is here to stay. When used judiciously it can add depth and subtlety to a web app. The problem, however, is that implementing parallaxing in a performant way can be challenging. In this article we’ll discuss a solution that is both performant and, just as importantly, works cross-browser.

TL;DR

  • Don’t use scroll events or background-position to create parallax animations.
  • Use CSS 3D transforms to create a more accurate parallax effect.
  • For Mobile Safari use position: sticky to ensure that the parallax effect gets propagated.

[…]

Both Scott Kellum and Keith Clark have done significant work in the area of using CSS 3D to achieve parallax motion, and the technique they use is effectively this:

  • Set up a containing element to scroll with overflow-y: scroll (and probably overflow-x: hidden).
  • To that same element apply a perspective value, and a perspective-origin set to top left, or 0 0.
  • To the children of that element apply a translation in Z, and scale them back up to provide parallax motion without affecting their size on screen.

The CSS for this approach looks like so:

Code language: CSS

.container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  perspective: 1px;
  perspective-origin: 0 0;
}
 
.parallax-child {
  transform-origin: 0 0;
  transform: translateZ(-2px) scale(3);
}

Which assumes a snippet of HTML like this:

Code language: HTML

<div class="container”>
  <div class="parallax-child”></div>
</div>

Using Quantity Queries to write content-aware CSS

Code language: CSS

:first-child:nth-last-child(4),
:first-child:nth-last-child(4) ~ * {
  /* Styles here */
}

This asks the question ‘Is this element the first-child and the fourth-last element that I’m working on OR does this element come after the first-child and the fourth-last element that I’m working on?’