Snippets

Using CSS Transitions on Auto Dimensions

We’ve all been there. You’ve got an element you want to be able to collapse and expand smoothly using CSS transitions, but its expanded size needs to be content-dependent. You’ve set transition: height 0.2s ease-out. You’ve created a collapsed CSS class that applies height: 0. You try it out, and… the height doesn’t transition. It snaps between the two sizes as if transition had never been set. After some fiddling, you figure out that this problem only happens when the height starts out or ends up as auto. Percentages, pixel values, any absolute units work as expected. But all of those require hard coding a specific height beforehand, rather than allowing it to naturally result from the size of the element content.

[…]

If you were hoping I had a magical, complete solution to this problem, I’m sorry to disappoint you. There’s no one solution that achieves the desired effect without downsides. There are, however, multiple workarounds that each come with a different set of advantages and disadvantages, and in most use cases at least one of them will get the job done in an acceptable manner. I’ll outline the major ones, and list out their ups and downs so you can hopefully pick the best one for your situation.

[…]

Technique 1: max-height

If you web search this problem, the max-height approach will probably be mentioned in all of the first five to ten results. It’s actually pretty unideal, but I thought it was worth including here for the sake of comparison.

It works like this: CSS values can only be transitioned to and from fixed unit values. But imagine we have an element whose height is set to auto, but whose max-height is set to a fixed value; say, 1000px. We can’t transition height, but we can transition max-height, since it has an explicit value. At any given moment, the actual height of the element will be the maximum of the height and the max-height. So as long as max-height’s value is greater than what auto comes out to, we can just transition max-height and achieve a version of the desired effect.

[…]

Technique 2: transform: scaleY()

[…]

Implementation works like this: we set a transition for the element’s transform property, then toggle between transform: scaleY(1) and transform: scaleY(0). These mean, respectively, “render this element at the same scale (on the y axis) that it starts out at” and “render this element at a scale of 0 (on the y axis)”. Transitioning between these two states will neatly “squish” the element to and from its natural, content-based size.

Technique 3: JavaScript

Managing a CSS transition in CSS would be ideal, but as we’re learning, sometimes it just isn’t entirely possible.

If you absolutely have to have smoothly collapsing sections, whose expanded size is completely driven by their content, and which other elements on the page will flow around as they transition, you can achieve that with some JavaScript.

The basic strategy is to manually do what the browser refuses to: calculate the full size of the element’s contents, then CSS transition the element to that explicit pixel size.

Using the Page visibility API to optimize an application for background

Web developers should be aware that users often have a lot of tabs open in the background and it can have a serious effect on power usage and battery life. Work in the background should be kept to a minimum unless it’s absolutely necessary to provide a particular user experience. The Page visibility API should be used to detect when page is the backgrounded and suspend all unnecessary work like visual updates.

Code language: JavaScript

var doVisualUpdates = true;
 
document.addEventListener('visibilitychange', function(){
  doVisualUpdates = !document.hidden;
});
 
function update() {
  if (!doVisualUpdates) {
    return;
  }
  doStuff();
}

hyperHTML: A Virtual DOM Alternative

The easiest way to describe hyperHTML is through an example.

Code language: JavaScript

// this is React's first tick example
// https://facebook.github.io/react/docs/state-and-lifecycle.html
function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}
setInterval(tick, 1000);
 
// this is hyperHTML
function tick(render) {
  render`
    <div>
      <h1>Hello, world!</h1>
      <h2>It is ${new Date().toLocaleTimeString()}.</h2>
    </div>
  `;
}
setInterval(tick, 1000,
  hyperHTML.bind(document.getElementById('root'))
);

Features

  • Zero dependencies and it fits in less than 2KB (minzipped)
  • Uses directly native DOM instead of inventing new syntax/APIs, DOM diffing, or virtual DOM
  • Designed for template literals, a templating feature built in to JS
  • Compatible with vanilla DOM elements and vanilla JS data structures *
  • Also compatible with Babel transpiled output, hence suitable for every browser you can think of

* actually, this is just a 100% vanilla JS utility, that’s why is most likely the fastest and also the smallest. I also feel like I’m writing Assembly these days … anyway …

Are We Breaking The Internet?

As more people and more devices get connected to the internet, the lure of centralizing control—which makes it easier for companies to manage them—is bumping its head against the initial design of the internet: to drive reliability and scalability. With every new largely centralized system that comes online, the internet becomes more brittle, as centralization creates an increased number of single points of failure.

CSS Grid Guides on MDN

A few weeks ago I was approached by the good people over at MDN, asking if I would be interested in writing a comprehensive resource for MDN on CSS Grid Layout. A series of guides to explain the grid specification with examples - ready for Grid shipping in Firefox 52 today.

I think that MDN is the best place for references and increasingly for learning web development, therefore I was very keen to add to that material and to create a learning resource for grid. Over the last couple of weeks I have written a book-worth of words and it is all available on MDN right now.

[…]

  1. Basics concepts of grid layout
  2. Relationship to other layout methods
  3. Line-based placement
  4. Grid template areas
  5. Layout using named grid lines
  6. Auto-placement in grid layout
  7. Box alignment in grid layout
  8. Grids, logical values and writing modes
  9. CSS Grid Layout and Accessibility
  10. CSS Grid Layout and Progressive Enhancement
  11. Realizing common layouts using grids

Text stroke with CSS

There is a non-standard way to stroke HTML text (SVG has a standard way). It’s not particularly new. There are -webkit- and -moz- prefixes for it. Jen Simmons recently posted about it, with an example:

Code language: CSS

span {
     -moz-text-fill-color: #fde;
  -webkit-text-fill-color: #fde;
     -moz-text-stroke-color: #666;
  -webkit-text-stroke-color: #666;
     -moz-text-stroke-width: 2px;  
  -webkit-text-stroke-width: 2px;
}

And she’s right:

This CSS isn’t fully-baked or fully-supported. But it’s good enough to be used today, especially since it’s simply offering a visual enhancement. It’s not mission critical to making a website usable.

I’d only perhaps add that if you were going to do something like add a stroke around white text, you could wrap it in a @supports to be extra sure it’ll be OK (just in case a browser exists that supports text-fill-color but not text-stroke-color) :

Code language: CSS

@supports 
  ((-webkit-text-stroke-color: #666)
  and
  (-webkit-text-fill-color: white))
  or
  ((-moz-text-stroke-color: #666)
  and
  (-moz-text-fill-color: white)) {
  span {
       -moz-text-fill-color: white;
    -webkit-text-fill-color: white;
       -moz-text-stroke-color: #666;
    -webkit-text-stroke-color: #666;
       -moz-text-stroke-width: 2px;  
    -webkit-text-stroke-width: 2px;
  }
}

See the link for more tricks, and the comments make a good point that you don’t have to use text-fill-color if you’re using @supports: just use color.

Dealing with long words in CSS

Code language: CSS

.hyphenate {
  overflow-wrap: break-word;
  word-wrap: break-word;
  -webkit-hyphens: auto;
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto;
}

This solution will show hyphens for every browser supporting it and will break lines in every other browser – perfect. [Although] I have tested this solution in 26 different browsers I am still not sure this will work 100% – if you find any edge case please let me know.