Journal tags: layout

24

sparkline

content-visibility in Safari

Earlier this year I wrote about some performance improvements to The Session using the content-visibility property in CSS.

If you say content-visibility: auto you’re telling the browser not to bother calculating the layout and paint for an element until it needs to. But you need to combine it with the contain-intrinsic-block-size property so that the browser knows how much space to leave for the element.

I mentioned the browser support:

Right now content-visibility is only supported in Chrome and Edge. But that’s okay. This is a progressive enhancement. Adding this CSS has no detrimental effect on the browsers that don’t understand it (and when they do ship support for it, it’ll just start working).

Well, that’s happened! Safari 18 supports content-visibility. I didn’t have to do a thing and it just started working.

But …I think I’ve discovered a little bug in Safari’s implementation.

(I say I think it’s a bug with the browser because, like Jim, I’ve made the mistake in the past of thinking I had discovered a browser bug when in fact it was something caused by a browser extension. And when I say “in the past”, I mean yesterday.)

So here’s the issue: if you apply content-visibility: auto to an element that contains an SVG, and that SVG contains a text element, then Safari never paints that text to the screen.

To see an example, take a look at the fourth setting of Cooley’s reel on The Session archive. There’s a text element with the word “slide” (actually the text is inside a tspan element inside a text element). On Safari, that text never shows up.

I’m using a link to the archive of The Session I created recently rather than the live site because on the live site I’ve removed the content-visibility declaration for Safari until this bug gets resolved.

I’ve also created a reduced test case on Codepen. The only HTML is the element containing the SVGs. The only CSS—apart from the content-visibility stuff—is just a little declaration to push the content below the viewport so you have to scroll it into view (which is when the bug happens).

I’ve filed a bug report. I know it’s a fairly niche situation, but there are some other issues with Safari’s implementation of content-visibility so it’s possible that they’re all related.

Speedier tunes

I wrote a little while back about improving performance on The Session by reducing runtime JavaScript in favour of caching on the server. This is on the pages for tunes, where the SVGs for the sheetmusic are now inlined instead of being generated on the fly.

It worked. But I also wrote:

A page like that with lots of sheetmusic and plenty of comments is going to have a hefty page weight and a large DOM size. I’ve still got a fair bit of main-thread work happening, but now the bulk of it is style and layout, whereas previously I had the JavaScript overhead on top of that.

Take a tune like Out On The Ocean. It has 27 settings. That’s a lot of SVG markup that needs to be parsed, styled and rendered, even if it’s inline.

Then I remembered a very handy CSS property called content-visibility:

It enables the user agent to skip an element’s rendering work (including layout and painting) until it is needed — which makes the initial page load much faster.

Sounds great! But there are two gotchas.

The first gotcha is that if a browser doesn’t paint the element, it doesn’t know how much space the element should take up. So you need to provide dimensions. At the very least you need to provide a height value. Otherwise when the element comes into view and gets rendered, it pushes down on the content below it. You’d see a sudden jump in the scrollbar position.

The solution is to provide a value for contain-intrinsic-size. If your content is dynamic—from, say, a CMS—then you’re out of luck. You don’t know how long the content is.

Luckily, in my case, I could take a stab at it. I know how many lines of sheetmusic there are for each tune setting. Each line takes up roughly the same amount of space. If I multiply that amount of space by the number of lines then I’ve got a pretty good approximation of the height of the sheetmusic. I apply this with the contain-intrinsic-block-size property.

So each piece of sheetmusic has an inline style attribute with declarations like this:

content-visibility: auto;
contain-intrinsic-block-size: 380px;

It works a treat. I did a before-and-after check with pagespeed insights on the page for Out On The Ocean. The “style and layout” part of the main thread work went down considerably. Total blocking time went from more than 600 milliseconds to less than 400 milliseconds.

Not a bad result for a little bit of CSS!

I said there was a second gotcha. That’s browser support.

Right now content-visibility is only supported in Chrome and Edge. But that’s okay. This is a progressive enhancement. Adding this CSS has no detrimental effect on the browsers that don’t understand it (and when they do ship support for it, it’ll just start working). I’ve said it before and I’ll say it again: the forgiving error-parsing in HTML and CSS is a killer feature of the web. Browsers just ignore what they don’t understand. That’s what makes progressive enhancement like this possible.

And actually, there’s something you can do for all browsers. Even browsers that don’t support content-visibility still understand containment. So they’ll understand contain-intrinsic-size. Pair that with a contain declaration like this to tell the browser that this chunk of content isn’t going to reflow or get repainted:

contain: layout paint;

Here’s what MDN says about contain:

The contain CSS property indicates that an element and its contents are, as much as possible, independent from the rest of the document tree. Containment enables isolating a subsection of the DOM, providing performance benefits by limiting calculations of layout, style, paint, size, or any combination to a DOM subtree rather than the entire page.

So if you’ve got a chunk of static content, you might as well apply contain to it.

Again, not bad for a little bit of CSS!

Five websites

Some lovely people have recently made some lovely websites.

Dan has launched his type foundry, Simple Type Co. and it’s gorgeous!

For as long as I’ve been making websites, Dan’s designs have been an inspiration: Corkd, Dribbble, his own website; whenever he unveils something it always sits just right with me.

Oh, and I love the tagline for Simple Type Co.:

Never perfect. Always a-okay.

Someone who is a perfectionist is Marcin. He’s been working on his book about keyboards for years now (the Kickstarter project will launch in February) and he’s made a stunning website for the book called Shift Happens. Click around and find out.

Mandy has a lovely new professional website, courtesy of Ethan. It’s called everything changes. I love the subtletly of the different colour schemes for dark and light modes. It’s almost as if Ethan knows a thing or two about responsive design.

Look! Jason has new professional website too. The text is just scrumptious. It’s almost as if Jason knows a thing or two about typography.

And look! Lynn has done it again—a new site design for a new year. Beautiful stuff, as always—have a look through the archive if you want to the creativity she puts into this every single year.

All of these people are my web design heroes.

Declarative design

I feel like in the past few years there’s been a number of web design approaches that share a similar mindset. Intrinsic web design by Jen; Every Layout by Andy and Heydon; Utopia by Trys and James.

To some extent, their strengths lie in technological advances in CSS: flexbox, grid, calc, and so on. But more importantly, they share an approach. They all focus on creating the right inputs rather than trying to control every possible output. Leave the final calculations for those outputs to the browser—that’s what computers are good at.

As Andy puts it:

Be the browser’s mentor, not its micromanager.

Reflecting on Utopia’s approach, Jim Nielsen wrote:

We say CSS is “declarative”, but the more and more I write breakpoints to accommodate all the different ways a design can change across the viewport spectrum, the more I feel like I’m writing imperative code. At what quantity does a set of declarative rules begin to look like imperative instructions?

In contrast, one of the principles of Utopia is to be declarative and “describe what is to be done rather than command how to do it”. This approach declares a set of rules such that you could pick any viewport width and, using a formula, derive what the type size and spacing would be at that size.

Declarative! Maybe that’s the word I’ve been looking for to describe the commonalities between Utopia, Every Layout, and intrinsic web design.

So if declarative design is a thing, does that also mean imperative design is also a thing? And what might the tools and technologies for imperative design look like?

I think that Tailwind might be a good example of an imperative design tool. It’s only about the specific outputs. Systematic thinking is actively discouraged; instead you say exactly what you want the final pixels on the screen to be.

I’m not saying that declarative tools—like Utopia—are right and that imperative tools—like Tailwind—are wrong. As always, it depends. In this case, it depends on the mindset you have.

If you agree with this statement, you should probably use an imperative design tool:

CSS is broken and I want my tools to work around the way CSS has been designed.

But if you agree with this statement, you should probably use a declarative design tool:

CSS is awesome and I want my tools to amplify the way that CSS had been designed.

If you agree with the first statement but you then try using a declarative tool like Utopia or Every Layout, you will probably have a bad time. You’ll probably hate it. You may declare the tool to be “bad”.

Likewise if you agree with the second statement but you then try using an imperative tool like Tailwind, you will probably have a bad time. You’ll probably hate it. You may declare the tool to be “bad”.

It all depends on whether the philosophy behind the tool matches your own philosophy. If those philosophies match up, then using the tool will be productive and that tool will act as an amplifier—a bicycle for the mind. But if the philosophy of the tool doesn’t match your own philosophy, then you will be fighting the tool at every step—it will slow you down.

Knowing that this spectrum exists between declarative tools and imperative tools can help you when you’re evaluating technology. You can assess whether a web design tool is being marketed on the premise that CSS is broken or on the premise that CSS is awesome.

I wonder whether your path into web design and development might also factor into which end of the spectrum you’d identify with. Like, if your background is in declarative languages like HTML and CSS, maybe intrisic web design really resonates. But if your background is in imperative languages like JavaScript, perhaps Tailwind makes more sense to you.

Again, there’s no right or wrong here. This is about matching the right tool to the right mindset.

Personally, the declarative design approach fits me like a glove. It feels like it’s in the tradition of John’s A Dao Of Web Design or Ethan’s Responsive Web Design—ways of working with the grain of the web.

Faulty logic

I’m a fan of logical properties in CSS. As I wrote in the responsive design course on web.dev, they’re crucial for internationalisation.

Alaa Abd El-Rahim has written articles on CSS tricks about building multi-directional layouts and controlling layout in a multi-directional website. Not having to write separate stylesheets—or even separate rules—for different writing modes is great!

More than that though, I think understanding logical properties is the best way to truly understand CSS layout tools like grid and flexbox.

It’s like when you’re learning a new language. At some point your brain goes from translating from your mother tongue into the other language, and instead starts thinking in that other language. Likewise with CSS, as some point you want to stop translating “left” and “right” into “inline-start” and “inline-end” and instead start thinking in terms of inline and block dimensions.

As is so often the case with CSS, I think new features like these are easier to pick up if you’re new to the language. I had to unlearn using floats for layout and instead learn flexbox and grid. Someone learning layout from scatch can go straight to flexbox and grid without having to ditch the cognitive baggage of floats. Similarly, it’s going to take time for me to shed the baggage of directional properties and truly grok logical properties, but someone new to CSS can go straight to logical properties without passing through the directional stage.

Except we’re not quite there yet.

In order for logical properties to replace directional properties, they need to be implemented everywhere. Right now you can’t use logical properties inside a media query, for example:

@media (min-inline-size: 40em)

That wont’ work. You have to use the old-fashioned syntax:

@media (min-width: 40em)

Now you could rightly argue that in this instance we’re talking about the physical dimensions of the viewport. So maybe width and height make more sense than inline and block.

But then take a look at how the syntax for container queries is going to work. First you declare the axis that you want to be contained using the syntax from logical properties:

main {
  container-type: inline-size;
}

But then when you go to declare the actual container query, you have to use the corresponding directional property:

@container (min-width: 40em)

This won’t work:

@container (min-inline-size: 40em)

I kind of get why it won’t work: the syntax for container queries should match the syntax for media queries. But now the theory behind disallowing logical properties in media queries doesn’t hold up. When it comes to container queries, the physical layout of the viewport isn’t what matters.

I hope that both media queries and container queries will allow logical properties sooner rather than later. Until they fall in line, it’s impossible to make the jump fully to logical properties.

There are some other spots where logical properties haven’t been fully implemented yet, but I’m assuming that’s a matter of time. For example, in Firefox I can make a wide data table responsive by making its container side-swipeable on narrow screens:

.table-container {
  max-inline-size: 100%;
  overflow-inline: auto;
}

But overflow-inline and overflow-block aren’t supported in any other browsers. So I have to do this:

.table-container {
  max-inline-size: 100%;
  overflow-x: auto;
}

Frankly, mixing and matching logical properties with directional properties feels worse than not using logical properties at all. The inconsistency is icky. This feels old-fashioned but consistent:

.table-container {
  max-width: 100%;
  overflow-x: auto;
}

I don’t think there are any particular technical reasons why browsers haven’t implemented logical properties consistently. I suspect it’s more a matter of priorities. Fully implementing logical properties in a browser may seem like a nice-to-have bit of syntactic sugar while there are other more important web standard fish to fry.

But from the perspective of someone trying to use logical properties, the patchy rollout is frustrating.

Utopia

Trys and James recently unveiled their Utopia project. They’ve been tinkering away at it behind the scenes for quite a while now.

You can check out the website and read the blog to get the details of how it accomplishes its goal:

Elegantly scale type and space without breakpoints.

I may well be biased, but I really like this project. I’ve been asking myself why I find it so appealing. Here are a few of the attributes of Utopia that strike a chord with me…

It’s collaborative

Collaboration is at the heart of Clearleft’s work. I know everyone says that, but we’ve definitely seen a direct correlation: projects with high levels of collaboration are invariably more successful than projects where people are siloed.

The genesis for Utopia came about after Trys and James worked together on a few different projects. It’s all too easy to let design and development splinter off into their own caves, but on these projects, Trys and James were working (literally) side by side. This meant that they could easily articulate frustrations to one another, and more important, they could easily share their excitement.

The end result of their collaboration is some very clever code. There’s an irony here. This code could be used to discourage collaboration! After all, why would designers and developers sit down together if they can just pass these numbers back and forth?

But I don’t think that Utopia will appeal to designers and developers who work in that way. Born in the spirit of collaboration, I suspect that it will mostly benefit people who value collaboration.

It’s intrinsic

If you’re a control freak, you may not like Utopia. The idea is that you specify the boundaries of what you’re trying to accomplish—minimum/maximum font sizes, minumum/maximum screen sizes, and some modular scales. Then you let the code—and the browser—do all the work.

On the one hand, this feels like surrending control. But on the other hand, because the underlying system is so robust, it’s a way of guaranteeing quality, even in situations you haven’t accounted for.

If someone asks you, “What size will the body copy be when the viewport is 850 pixels wide?”, your answer would have to be “I don’t know …but I do know that it will be appropriate.”

This feels like a very declarative way of designing. It reminds me of the ethos behind Andy and Heydon’s site, Every Layout. They call it algorithmic layout design:

Employing algorithmic layout design means doing away with @media breakpoints, “magic numbers”, and other hacks, to create context-independent layout components. Your future design systems will be more consistent, terser in code, and more malleable in the hands of your users and their devices.

See how breakpoints are mentioned as being a very top-down approach to layout? Remember the tagline for Utopia, which aims for fluid responsive design?

Elegantly scale type and space without breakpoints.

Unsurprisingly, Andy really likes Utopia:

As the co-author of Every Layout, my head nearly fell off from all of the nodding when reading this because this is the exact sort of approach that we preach: setting some rules and letting the browser do the rest.

Heydon describes this mindset as automating intent. I really like that. I think that’s what Utopia does too.

As Heydon said at Patterns Day:

Be your browser’s mentor, not its micromanager.

The idea is that you give it rules, you give it axioms or principles to work on, and you let it do the calculation. You work with the in-built algorithms of the browser and of CSS itself.

This is all possible thanks to improvements to CSS like calc, flexbox and grid. Jen calls this approach intrinsic web design. Last year, I liveblogged her excellent talk at An Event Apart called Designing Intrinsic Layouts.

Utopia feels like it has the same mindset as algorithmic layout design and intrinsic web design. Trys and James are building on the great work already out there, which brings me to the final property of Utopia that appeals to me…

It’s iterative

There isn’t actually much that’s new in Utopia. It’s a combination of existing techniques. I like that. As I said recently:

I’m a great believer in the HTML design principle, Evolution Not Revolution:

It is better to evolve an existing design rather than throwing it away.

First of all, Utopia uses the idea of modular scales in typography. Tim Brown has been championing this idea for years.

Then there’s the idea of typography being fluid and responsive—just like Jason Pamental has been speaking and writing about.

On the code side, Utopia wouldn’t be possible without the work of Mike Reithmuller and his breakthroughs on responsive and fluid typography, which led to Tim’s work on CSS locks.

Utopia takes these building blocks and combines them. So if you’re wondering if it would be a good tool for one of your projects, you can take an equally iterative approach by asking some questions…

Are you using fluid type?

Do your font-sizes increase in proportion to the width of the viewport? I don’t mean in sudden jumps with @media breakpoints—I mean some kind of relationship between font size and the vw (viewport width) unit. If so, you’re probably using some kind of mechanism to cap the minimum and maximum font sizes—CSS locks.

I’m using that technique on Resilient Web Design. But I’m not changing the relative difference between different sized elements—body copy, headings, etc.—as the screen size changes.

Are you using modular scales?

Does your type system have some kind of ratio that describes the increase in type sizes? You probably have more than one ratio (unlike Resilient Web Design). The ratio for small screens should probably be smaller than the ratio for big screens. But rather than jump from one ratio to another at an arbitrary breakpoint, Utopia allows the ratio to be fluid.

So it’s not just that font sizes are increasing as the screen gets larger; the comparative difference is also subtly changing. That means there’s never a sudden jump in font size at any time.

Are you using custom properties?

A technical detail this, but the magic of Utopia relies on two powerful CSS features: calc() and custom properties. These two workhorses are used by Utopia to generate some CSS that you can stick at the start of your stylesheet. If you ever need to make changes, all the parameters are defined at the top of the code block. Tweak those numbers and watch everything cascade.

You’ll see that there’s one—and only one—media query in there. This is quite clever. Usually with CSS locks, you’d need to have a media query for every different font size in order to cap its growth at the maximum screen size. With Utopia, the maximum screen size—100vw—is abstracted into a variable (a custom property). The media query then changes its value to be the upper end of your CSS lock. So it doesn’t matter how many different font sizes you’re setting: because they all use that custom property, one single media query takes care of capping the growth of every font size declaration.

If you’re already using CSS locks, modular scales, and custom properties, Utopia is almost certainly going to be a good fit for you.

If you’re not yet using those techniques, but you’d like to, I highly recommend using Utopia on your next project.

Designing Intrinsic Layouts by Jen Simmons

Alright, it’s time for the final talk of day one of An Event Apart in Seattle. The trifecta of CSS talks is going to finish with Jen Simmons talking about Designing Intrinsic Layouts. Here’s the description:

Twenty-five years after the web began, we finally have a real toolkit for creating layouts. Combining CSS Grid, Flexbox, Multicolumn, Flow layout and Writing Modes gives us the technical ability to build layouts today without the horrible hacks and compromises of the past. But what does this mean for our design medium? How might we better leverage the art of graphic design? How will we create something practical, useable, and realistically doable?

In a talk full of specific examples, Jen will walk you through the thinking process of creating accessible & reusable page and component layouts. For the last four years, Jen’s been getting audiences excited about what, when, and why. Now it’s time for how.

I’m not sure if live-blogging is going to work given the visual nature of this talk, but I’ll give it a try…

How many of us have written CSS using display: grid? Quite a few. How many people feel they have a good grip on it? Not so many.

Jen has spent the last few years encouraging people to really push the boundaries of graphic design on the web now that we have the tools to do so in CSS. But Jen is not here today to talk about amazing new things. Instead she’s going to show the “how?” The code is on labs.jensimmons.com.

Let’s look at laying out a header. You might have a header element with a logo image, the site name in an h1, and a nav element with the navigation. The logo, the site name, and the navigation are direct children of the parent header. By default we get everything stacked vertically.

<header role="banner">
    <img class="logo" src="..." alt="...">
    <h1>Site title</h1>
    <nav>
        <ul>
            <li><a href="...">Home</a></li>
            <li><a href="...">Episodes</a></li>
            <li><a href="...">Guests</a></li>
            <li><a href="...">Subscribe</a></li>
            <li><a href="...">About</a></li>
        </ul>
    </nav>
</header>

Why should we care about starting with semantic HTML? It matters for reusability and accessibility, but also for reader modes in browsers. These tools remove the cruft. If you mark up your content well, it will play nicely with reader modes. Interestingly, there are no metrics around how many people are using reader modes (by design). Mozilla has a product called Pocket that’s a “read later” app. It can also turn saved articles into a podcast for you. Well marked up content matters for audio playback.

Now let’s start applying some CSS. Fonts, colours, stuff like that. Everything is still stacking vertically though. It’s flow content. This can be our fallback layout. Now let’s apply our own layout. We could use float: left on the logo. Now we need some margins. We can try applying widths and floats to the h1 and the nav. Now we need a clearfix to get the parent to stretch to the full height of the content. It’s hacky. floats suck. But it’s all we had until we got flexbox. But even using flexbox for this kind of layout is a hack too. What we really need is CSS grid.

Apply display: grid to the header. Use Firefox’s dev tools to inspect the grid. Seeing the grid helps in understanding what’s going on. We’ve got three grid items in three separate rows. Notice that we don’t have margin collapsing any more. We can get rid of margins and use grid-gap instead. But we want is three columns, not three rows. We’ll try:

grid-template-columns: 1fr 1fr 1fr;

Looks okay. Not exactly the spacing we want though. We want the logo and the navigation to take up less space than the site name. We could translate our old percentage values into fr equivalents. 8% becomes 8fr. 75% becomes 75fr. 17% becomes 17fr. But the logo and the nav never shrink below their actual size. Layout isn’t working like we’re used to. The content will never get smaller than the minimum content size. So the amount of space assigned to each column is no longer linear.

Let’s change those fr units to percentages. Now we need to get rid of our gaps. But now when the layout gets small, everything squishes up. This is what we need breakpoints for. But now we can do something else. Let’s make the logo max-content. That column will now be the size of the logo. The other columns can remain `fr:

header {
    grid-template columns: max-content 3fr 1fr;
}

Let’s also define the last one—the navigation—as max-content. We can toss auto in for the middle content (the site name):

header {
    grid-template columns: max-content auto max-content;    }

Let’s layout the navigation horizontally. The best tool for this is flexbox. The li elements are the flex items. So the ul needs to be the flex container.

ul {
    display: flex;
}

Looking good. Let’s allow items to wrap onto another line:

ul {
    display: flex;
    flex-wrap: wrap;
}

Let’s change that navigation from max-content to auto so that it doesn’t get too long:

header {
    grid-template columns: max-content auto auto;   }

(How you want the navigation items to wrap determines whether you use flexbox or grid. Both are perfectly valid choices. There’s nothing wrong with using grid for the small stuff.)

Just look at how little code we need for this layout!

Let’s try a different layout. We’ll put the navigation on a new row.

header {
    grid-template-columns: min-content auto;
    grid-template-rows: auto auto
}

Let’s get the logo to span across both rows:

.logo {
    row-span: 2;
}

Need to finesse the alignment of the navigation? No problem. Play with align-self property on the nav element.

Again, look at how little code this is!

But these layouts are safe. We need to break out of our habits. What about disjointed text? Let’s take the h1. Apply some typography and colour. Also apply overflow-wrap: anywhere. Now the text can break within words.

We can take this further. But to do that, we have to wrap all of my letters in separate spans. Yuck!

Apply display: grid to the h1 that contains all those span children. Say grid-template-columns: repeat(8, 1fr) to make an eight-column repeating grid.

Let’s make it more interesting. We can target each individual letter with grid-column and grid-row. There are many ways to tell the browser where to place grid items. We can tell them the start lines. By default it will take up one cell.

Let’s add some images. Let’s rotate items. Place items wherever we want them. Mess around with the units to see what happens. Play with opacity when elements overlap. See the possibilities!

But, people cry, what about Internet Explorer? Use @supports

/* code for every browser */

@supports (display: grid) {
    /* code for modern browsers */
}

Set up a fallback outside the @supports block. Toggle grid on and enough in dev tools to see how the fallback will look. If this kind of thinking is new to you, please watch youtube.com/layoutland where Jen talks about resilient CSS.

Let’s try something else. Jen got an email announcement for an event. It had an interesting bit of layout with some text overlapping an image.

Mark up the content: some headings and images. By default the images are displayed inline. The headings are displayed as blocks.

Think about where your grid lines will need to go. How many lines will you need? How about setting your columns with 1fr 3fr 3fr 1fr? Now how many rows do you need? You define and the grid on the container and tell the items where to go. Again, it’s not much code. Tweak it. How about setting the columns to be 1fr minmax(100px, 400px) min-content? You have to mess around to see what’s possible. You can use all sorts of units for columns: fixed lengths (pixels, ems, rems), min-content, max-content, percentages, fr units, minmax(), and auto. Play around with the combinations.

Jen shows a whole bunch of her demos. Check them out. Use web inspector to play around with them.

And with that, the first day of An Event Apart Seattle is done!

Making Things Better: Redefining the Technical Possibilities of CSS by Rachel Andrew

The CSStastic afternoon of day one of An Event Apart in Seattle continues with Rachel Andrew. Her talk is Making Things Better: Redefining the Technical Possibilities of CSS. The description reads:

For years we’ve explained that the web is not like print; that a particular idea is not how things work on the web; that certain things are simply not possible. Over the last few years, rapid browser implementation of advances in CSS have given us the ability to do many of these previously impossible things. We can use our new powers to build the same designs faster, or we can start to ask ourselves what we might do if we were solving these problems afresh.

In this talk, Rachel will look at the things coming into browsers right now which change the way we see web design. CSS subgrids allowing nested grids to use the track definition of their parent; logical properties and values moving the web away from the physical dimensions of a computer screen; screen experiences which behave more like an app, or even paged media, due to scroll snapping and multidimensional control. By understanding the new medium of web design we can start to imagine the future, and even help to shape it.

I’m not sure if it even makes sense to try to live-blog a code talk, but I’ll give it my best shot…

Rachel has been talking about CSS at An Event Apart for over three years now. Our understanding of the possibilities of CSS has changed a lot in that time. Our use of floats for layout is being consigned to history. It’s no less monumental than the change from tables to CSS. Tableless web design often meant simplifying our designs. We were used to designing in a graphic design tool and then slicing it up into table cells. CSS couldn’t give us the same fine-grained control so we simplified our designs. It got us to start thinking of the web as its own medium. That idea really progressed with responsive web design.

But perhaps us CSS advocates downplayed some of the issues. We weren’t trying to create new CSS, we were just trying to get people to use CSS.

What we term “good web design” is based in the technical limitations of CSS. We say “the web is not print” when we see a design that’s quite print-like. People expect to have to hack at CSS to get it to do what we want. But times have changed. We have solved many of those problems (but that doesn’t mean we got all of them!).

Rachel spends a lot of time telling designers: you never know how tall anything is on the web. It used to be a real challenge to get the top and bottom of boxes to line up. We’d have to fix the height of the boxes. And if too much content goes in, the content overflows. Then we end up limiting the amount of content at the CMS side. We hacked around the problem. A technical limitation influenced our design, and even our content management. Then we got flexbox. Not only did the problem disappear, but the default behaviour is exactly what we struggled with for years: equal height columns.

How big is this box? You’ve seen the “CSS is awesome mug”, right?

Our previous layout systems relied on percentage lengths for widths. Those values had to add up to 100%, and no more. People tried to do the same thing with flexbox. People made “grid systems” with flexbox that gave widths to everything. “Flexbox is weird!”, people said. But the real problem is that flexbox is not the layout method you think it is. It’s for taking a bunch of oddly-sized things and returning the most reasonable layout for those things. It assigns space in a smart way. That solves the problem of needing to give everthing a width. It figures it out for you. If you decide to put widths on everything, you’re kind of working against flexbox.

We’re so used to having to hack everything in CSS, we had to take a step back with flexbox and realise that hacks aren’t necessary.

CSS tries to avoid data loss. That’s why the “CSS is awesome” text overflows the box. You don’t want the text to vanish. Visible overflow is messy, but it’s better than making some content disappear.

In the box alignment specification, there’s the concept of safe and unsafe alignment. Safe:

.container {
    display: flex;
    flex-direction: column;
    align-items: safe center;
}

You give the browser permission to align items to the start if necessary. But you can override that with unsafe:

.container {
    display: flex;
    flex-direction: column;
    align-items: unsafe center;
}

Overflow is going to happen. Now it’s up to you what happens when it does.

The “content honking out of the box” problem described in the “CSS is awesome” meme is now controlled with min-content:

width: min-content;

The box expands to encompass the widest content.

You have many choices. But what if the text isn’t running left to right? It might not be a problem we run into for English text. For years, CSS had that English-centric assumption baked in. Now CSS has been updated to not make that assumption. The web is not left to right. Flexbox and grid take an agnostic approach to the writing mode of the document. There’s no “top”, “bottom”, “left” or “right”. There’s “start”, “end”, “inline” and “block”. Now we have a new spec for logical properties and values. It maps old physical values (top, bottom, etc.) to the newer agnostic values.

So even if you use writing-mode to flip direction, width is still a width. Use inline-size instead of width and everything keeps working: the width maps to height when you apply a different writing-mode value. Eventually we’ll use those flow-relative values more than the old values. Solutions need to include different writing modes.

There is no fold. We’ve said that for years, right? But we know where the fold is. We’ve got viewport units that represent the width and height of the browser viewport. We can start to make designs that make use of the viewport. You can size a screen full of images exactly to fit the visible space. Combine it with scroll-snap to get the page views to snap as the user scrolls. You get paged layout. That’s interesting for Rachel because she’s used to designing for paged layout in print versus continuous layout on the web.

What’s next for CSS grid? Grid layout has been the biggest problem-solver of recent years. But that doesn’t mean it has solved all the layout problems. New problems appear as we start to work with CSS grid. We often end up nesting grids. But the nested grids don’t have any knowledge of one another. We’re back to: you never know how tall things are on the web. We need a way to have a relationship. Some kind of, I don’t know, subgrid.

You could use display: contents. It removes a box from the visual display allowing grandchildren to act like children. The browser support is good, but there’s a stonking accessibility bug so don’t use it in production. Also you can’t apply visual styles to anything that’s got display: contents on it. But grid-template-rows: subgrid will solve this problem. The spec is in a good shape. We’re waiting for the first browser implementations.

You will hit problems. Find new technical limitations. It’s just that we can’t do that stuff yet. We get the new stuff when we create it. Write up the problems you come across.

We’re finding the edges. Rachel is going to share her problems.

Rachel wants to put some text into her image grid. No problem. But then if there’s too much text, it might not fit in a height-restricted row. We can adjust the row to not be height-restricted, but then we lose the nice viewport-fitting layout.

In continuous media—which is what the web is—content inside multicol gets longer and longer. You can fix the height of the container but then the columns get created horizontally. What if you could say, I want my multicol container to be, say 100vh high, but if the content overlows, create a new 100vh high container below. Overflow in the block dimension. Maybe that’ll be in the next version of the multicol spec.

Multicol doesn’t solve Rachel’s image grid situation. What she needs is a way for the text to fill up a box and then flow into another box. The content needs to be semantically marked up—not broken into separate chunks for layout—and we want the browser to figure out where to break that content and fill up available space.

It comes as a surprise to people that a lot of paged media—books, magazines—are laid out with CSS. It’s in the paged media module. Prince is a good example of a user agent that supports paged media. There’s the concept of a page box: a physical page into which content can go. You get to define the boxes with physical dimensions like inches or centimeters. You create a bunch of margin boxes with generated content. Enough pages are created to hold all the content. You create your page model and flow the content through it.

Maybe apps and websites with defined screens are not that different from paged contexts. There have been attempts to create CSS specs that would allow this kind of content-flowing behaviour. CSS regions was one attempt. There was -ms-flow-into and -ms-flow-from in the IE and Edge implementations. You had to apply -ms-flow-into to an iframe element.

Regions needs ready-prepared boxes for the content to flow into. But how can you know how many boxes to prepare in advance? You don’t know how big things will be on the web. Rachel has been told that there’s nothing wrong with the CSS regions spec because you can define a final bucket for all leftover content. That doesn’t seem like a viable solution.

CSS regions predated CSS grid and didn’t take off. Now that we’ve got grid, something like regions makes a lot of sense.

Web design has been involved in a constant battle with overflow. Whether it’s overflowing boxes, or there (not) being a fold, or multicol layout. Rachel thinks we can figure out a way to get regions to work. Perhaps regions paved the way for something better. Maybe it was just ahead of its time. There are a lot of things hidden away in CSS specs that never made it out: things that didn’t make sense until more advanced CSS came along.

Regions—like multicol—relies on fragmentation. Ever tried to stop a heading behind the last thing on a page in a print stylesheet? We need good support for break-inside, break-before, and break-after.

We create new things to solve problems. Maybe you don’t see the value of something like regions, but I bet there’s been something where you thought “I wish CSS could do this!”.

Rob wrote up a problem that he had with trying to have a floated element maintain its floatiness inside a grid. He saw it as a grid problem. Rachel saw it as an exclusions problem. Rob’s write-up was really valuable to demonstrate the need for exclusions. Writing things up is hugely valuable for pushing things forward. Write up your ideas—they’ll show us the use case.

Ask “why can’t I do that?” Let’s not fall into the temptation of making things grid-like just because we have CSS grid now. Keep pushing at the boundaries.

Many of things Rachel has shown—grid, exclusions, regions—were implemented by Microsoft. With Edge moving to a Chromium rendering engine, we must make sure that we maintain diversity of thought in the standards process. Voices other than those of rendering engines need to contribute to the discussion.

At a W3C meeting or standards discussion, the room should not be 60-70% Googlers.

More than ever, the web needs diversity of thought. Rachel isn’t having a dig at Google. This isn’t a fight between good and evil. It’s a fight against any monoculture. So please contribute. Get involved. Together we can work for the future of the web platform.

CSS grid in Internet Explorer 11

When I was in Boston, speaking on a lunchtime panel with Rachel at An Event Apart, we took some questions from the audience about CSS grid. Inevitably, a question about browser support came up—specifically about support in Internet Explorer 11.

(Technically, you can use CSS grid in IE11—in fact it was the first browser to ship a version of grid—but the prefixed syntax is different to the standard and certain features are missing.)

Rachel gave a great balanced response, saying that you need to look at your site’s stats to determine whether it’s worth the investment of your time trying to make a grid work in IE11.

My response was blunter. I said I just don’t consider IE11 as a browser that supports grid.

Now, that might sound harsh, but what I meant was: you’re already dividing your visitors into browsers that support grid, and browsers that don’t …and you’re giving something to those browsers that don’t support grid. So I’m suggesting that IE11 falls into that category and should receive the layout you’re giving to browsers that don’t support grid …because really, IE11 doesn’t support grid: that’s the whole reason why the syntax is namespaced by -ms.

You could jump through hoops to try to get your grid layout working in IE11, as detailed in a three-part series on CSS Tricks, but at that point, the amount of effort you’re putting in negates the time-saving benefits of using CSS grid in the first place.

Frankly, the whole point of prefixed CSS is that is not used after a reasonable amount of time (originally, the idea was that it would not be used in production, but that didn’t last long). As we’ve moved away from prefixes to flags in browsers, I’m seeing the amount of prefixed properties dropping, and that’s very, very good. I’ve stopped using autoprefixer on new projects, and I’ve been able to remove it from some existing ones—please consider doing the same.

And when it comes to IE11, I’ll continue to categorise it as a browser that doesn’t support CSS grid. That doesn’t mean I’m abandoning users of IE11—far from it. It means I’m giving them the layout that’s appropriate for the browser they’re using.

Remember, websites do not need to look exactly the same in every browser.

New tools for art direction on the web

I’m in Boston right now, getting ready to speak at An Event Apart. This will be my second (and last) Event Apart of the year—the other time was in Seattle back in April. After that event, I wrote about how inspired I was:

It was interesting to see repeating, overlapping themes. From a purely technical perspective, three technologies that were front and centre were:

  • CSS grid,
  • variable fonts, and
  • service workers.

From listening to other attendees, the overwhelming message received was “These technologies are here—they’ve arrived.”

I was itching to combine those technologies on a project. Coincidentally, it was around that time that I started planning to publish The Gęsiówka Story. I figured I could use that as an opportunity to tinker with those front-end technologies that I was so excited about.

But I was cautious. I didn’t want to use the latest exciting technology just for the sake of it. I was very aware of the gravity of the material I was dealing with. Documenting the story of Gęsiówka was what mattered. Any front-end technologies I used had to be in support of that.

First of all, there was the typesetting. I don’t know about you, but I find choosing the right typefaces to be overwhelming. Despite all the great tips and techniques out there for choosing and pairing typefaces, I still find myself agonising over the choice—what if there’s a better choice that I’m missing?

In this case, because I wanted to use a variable font, I had a constraint that helped reduce the possibility space. I started to comb through v-fonts.com to find a suitable typeface—I was fairly sure I wanted a serious serif.

I had one other constraint. The font file had to include English, Polish, and German glyphs. That pretty much sealed the deal for Source Serif. That only has one variable axis—weight—but I decided that this could also be an interesting constraint: how much could I wrangle out of a single typeface just using various weights?

I ended up using font weights of 75, 250, 315, 325, 340, 350, 400, and 525. Most of them were for headings or one-off uses, with a font-weight of 315 for the body copy.

(And can I just say once again how impressed I am that the founding fathers of CSS were far-sighted enough to keep those font weight ranges free for future use?)

Getting the typography right posed an interesting challenge. This was a fairly long piece of writing, so it really needed to be readable without getting tiring. But at the same time, I didn’t want it to be exactly pleasant to read—that wouldn’t do the subject matter justice. I wanted the reader to feel the seriousness of the story they were reading, without being fatigued by its weight.

Colour and type went a long way to communicating that feeling. The grid sealed the deal.

The Gęsiówka Story is mostly one single column of text, so on the face of it, there isn’t much opportunity to go crazy with CSS Grid. But I realised I could use a grid to create a winding effect for the text. I had to be careful though: I didn’t want it to become uncomfortable to read. I wanted to create a slightly unsettling effect.

Every section element is turned into a seven-column grid container:

section {
    display: grid;
    grid-column-gap: 2em;
    grid-template-columns: 2em repeat(5, 1fr) 2em;
}

The first and last columns are the same width as the gutters (2em), effectively creating “outer” gutters for the grid. Each paragraph within the section takes up six of the seven columns. I use nth-of-type to alternate which six columns are used (the first six or the last six). That creates the staggered indendation:

section > p {
    grid-column: 1/7;
}
section > p:nth-of-type(even) {
    grid-column: 2/8;
}

Staggered grid.

That might seem like overkill just to indent every second paragraph by 4em, but I then used the same grid dimensions to layout figure elements with images and captions.

section > figure {
    display: grid;
    grid-column-gap: 2em;
    grid-template-columns: 2em repeat(5, 1fr) 2em;
}

Then I can lay out differently proportioned images across different ranges of the grid:

section > figure.landscape > img {
    grid-column: 1/5;
}
section > figure.landscape > figcaption {
    grid-column: 5/8;
}
section > figure.portrait > img {
    grid-column: 1/4;
}
section > figure.portrait > figcaption {
    grid-column: 4/8;
}

Because they’re positioned on the same grid as the paragraphs, everything lines up nicely (and yes, if subgrid existed, I wouldn’t have to redeclare the grid dimensions for the figures).

Finally, I wanted to make sure that the whole thing could be read offline. After all, once you’ve visited the URL once, there’s really no reason to make any more requests to the server. Static documents—and books—are the perfect candidates for an “offline first” approach: always look in the cache, and only go to the network as a last resort.

In this case I used a variation of my minimal viable service worker script, and the result is a very short set of instructions. There’s a little bit of pre-caching going on: I grab the variable font and the HTML page itself (which includes the CSS inlined).

So there you have it: variable fonts, CSS grid, and service workers: three exciting front-end technologies, all of which can be applied as progressive enhancements on top of the core content.

Once again, I find that it’s personal projects that offer the most opportunities to try out new or interesting techniques. And The Gęsiówka Story is a very personal project indeed.

Good griddance

I’m not great at estimation, but I still try to do it on any project I’m working, even if it’s just for my own benefit. I break down different bits of the work, and ask myself two questions:

  1. How important is this?
  2. How long will it take?

If I were smart, I’d plot the answers on a graph. I start doing the important stuff, beginning with whatever won’t take too long. Then I’ve got a choice: either do the stuff that’s not all that important, but won’t take long—or do the stuff that will take quite a while, but is quite important. Finally, there’s stuff that’s not important and will take quite a while to do. I leave that to the end. If it never ends up getting done, it’s not the end of the world.

I guess it’s not really about estimation; it’s more about prioritisation.

Anyway, I’m working on a fun little project right now—the website for one of Clearleft’s many excellent events. There was one particular part of the design that I had estimated would take quite a while to do, so I didn’t get around to it until today. It was a layout that I figured would take maybe half a day of wrangling CSS.

I used CSS grid and I was done in five minutes. That’s not an exaggeration. It was literally five minutes.

I thought to myself, “Well, I want these elements to be arranged in two rows of three columns, but I want that particular one to always be in the last column of the top row.”

Normally my next step would be to figure out how to translate those wishes into floats and clears, or maybe flexbox. But this time, there was almost no translation. I could more or less write the CSS like I would write English.

I want these elements to be arranged in rows of three columns.

display: grid;
grid-template-columns: 1fr 1fr fr

I want that particular one to always be in the last column of the top row.

grid-row: 1;
grid-column: 3;

That was it. I was done.

I think I may need to recalibrate the estimation part of my brain to account for just how powerful CSS grid is.

Everything You Know About Web Design Just Changed by Jen Simmons

Alright! It’s time for the final talk of the day at An Event Apart Seattle (Special Edition). Jen is wrapping up a CSStastic afternoon with her talk Everything You Know About Web Design Just Changed. These are my notes…

Ready for another hour of layout in CSS? Well, Jen will be showing no code in this talk. She’s actually nervous about this particular talk. Is she really planning to say “Everything about web design just changed”? That sounds so clickbaity! But she really believes we’re at an inflection point. This may be the sixth such point in the history of the web. One of those points where everything changes and we swap out our techniques.

For the last few years, we’ve been saying that everything changed when mobile came along. But actually, the real fight has been going on for longer than that. It’s the battle between wanting art and dealing with how the web works.

There’s a seminal book called Creating Killer Websites by David Siegel from 1996. In it, he describes the first time he saw the same site in two different browsers. His reaction was panic. The web gave control to the user. David Siegel wanted more control. And that’s how we got spacer gifs and tables for layout.

What are the five major changes in the history of web design?

  1. Simple HTML. There was only one kind of layout: flow layout. There’s no CSS, but the browser is still thinking of everything has having a box. Text takes up as much space as it needs. Images take up as much space as their size. This is flow. There wasn’t much you could do until tables came along. They were created for tabular content but abused for layouts. The “We need art!” crowd used what was available to them at the time. Lots of slicing and dicing.
  2. Flash. It was hard to get HTML tables to work in multiple browsers. Flash seemed like an amazing chance to start over. And we could do things that were previously only possible in CD-ROMs. As a designer, you take an element and place it where you want to go on the stage (the UI tradition that goes all the way back to Xerox PARC). We made some crazy sites, explored a lot of possibilities, and got a lot of control. But the downside was the lack of accessibility. We went back to getting to grips with the web as its own medium. Jeffrey’s book, Designing With Web Standards, was a rallying cry to allow HTML to return to doing what it was meant to.
  3. Fluid Layouts. This was a return to the way the web always behaved—content takes up as much room as it needs to. But this time there’s a certain amount of control over how things are laid out. Still, we pretended that nobody has screens smaller than 640 pixels or bigger than 1024 pixels. We still live with the idea of fluid columns today.
  4. Fixed-Width Layouts. The “We need art!” crowd wanted more control than fluid layouts offered. We pretended that everyone’s screen was at least 640 pixels, or later 800 pixels, or later 1024 pixels.
  5. Responsive Web Design. Unveiled by Ethan at An Event Apart Seattle in 2011: flexible grid; flexible images; media queries. It’s a return to fluid layouts, but the addition of media queries gives us more control. The idea of fluid image was a bit radical. Up until that point, we thought of images as always being their intrinsic size. But something Ethan said that day was “It’s not just about layout.” And it’s true. For the last eight years, it’s been about more than layout. You set out to redesign your website and end up redesigning your whole business. Responsive web design is, frankly, what the web is now.

But let’s talk about layout. What’s next? Intrinsic Web Design.

Why a new name? Why bother? Well, it was helpful to debate fluid vs. fixed, or table-based layouts: having words really helps. Over the past few years, Jen has needed a term for “responsive web design +”.

Responsive web design has flexible images. Intrinsic web design has flexible images …or fixed images. Whichever you want.

Responsive web design has a fluid columns. Intrinsic web design has fluid columns and rows.

Responsive web design uses media queries. Intrinsic web design doesn’t necessarily need them.

The name comes from words that have been floating in the ether. In Rachel’s talk, the words “sizing” and “intrinsic” came up a lot. This is about the nature of the web.

Let’s look at images specifically. Before responsive web design, images overflow their container if they are bigger than the container. Fluid images (as used in responsive web design) shrink and grow depending on the size of their container. You can also make images fluid in a vertical direction. If we make the image fluid vertically and horizontally, the image looks distorted. But now if we use object-fit: cover we can specify how we want the image to react.

Fixed or fluid? With grid layout, you can mix fixed and fluid. You can make a layout fluid until it hits a minimum size, at which point it stays fixed.

There are four stages of squishiness:

  1. fixed
  2. fr units (fluid)
  3. minmax()(fluid until fixed)
  4. auto (a return to flow)

That’s a powerful set of tools that may take us years to explore.

We can do truly two-dimensional layouts: rows and columns. Every one of those four stages of squishiness works for rows as well as columns. This means we can create intentional white space. Jen made a video about this and got the response that this was always possible, but it’s different now: it’s more intentional. You can set heights and widths.

We can have nested contexts now:

  1. Flow
  2. Flexbox (formatting context)
  3. Grid (formatting context)
  4. Multicolumn (formatting context)

Floats never created a new formatting context, which is why used clearfix. Now we don’t need hacks. You can mix and match, choosing the best layout tool for the job at hand. You can have a grid layout that has flexbox items within it. The Firefox dev tools allow you to inspect each layout type separately. You can use the nightly build to get the latest tools.

Then we’ve got ways to contract and expand content. We have more options now. For a while, we’ve had the option to squish and grow (e.g. with fluid images). Another is wrapping and reflowing (like we can do with text). Another option now is to add and remove whitespace. Maybe the content size doesn’t need to change; the whitespace shrinks and grows instead. An even more radical option now is to have things slide behind one another and overlap deliberately.

Sometimes you don’t even need to use media queries (meaning we’ve effectively got container queries). But we can still use media queries, as needed, to tweak the details.

So intrinsic web design is:

  1. Fluid and fixed
  2. Stages of squishiness
  3. Truly two-dimensional layouts
  4. Nested contexts
  5. Expand and contract content
  6. Media queries, as needed

We have a whole new sandbox that we can play in. You can find examples at labs.jensimmons.com.

See also:

Fit For Purpose: Making Sense of the New CSS by Eric Meyer

Time for even more CSS goodness at An Event Apart Seattle (Special Edition). Eric’s talk is called Fit For Purpose: Making Sense of the New CSS. Here are my notes…

Eric isn’t going to dive quite as deeply as Rachel, but he is going to share some patterns he has used.

Feature queries

First up: feature queries! Or @supports, if you prefer. You can ask a browser “do you support this feature?” If you haven’t used feature queries, you might be wondering why you have to say the property and the value. Well, think about it. If you asked a browser “do you support display?”, it’s not very useful. So you have to say “do you support display: grid?”

Here’s a nice pattern from Lea Verou for detecting support for custom properties:

@supports (--css: variables)

Here’s a gotcha:

@supports (clip-path: polygon())

That won’t work because polygon() is invalid. This will work:

@supports (clip-path: polygon(0 0))

So to use feature queries, you need to understand valid values for properties.

You can chain feature queries together, or just pick the least-supported thing you’re testing for and test just for that.

Here’s a pattern Eric used when he only wanted to make text sideways, but only if grid is supported:

@supports (display: grid) {
    ...
    @supports (writing-mode: sideways-lr) {
        ...
    }
}

That’s functionally equivalent to:

@supports (display: grid) {
    ...
}
@supports (display:grid) and (writing-mode: sideways-lr) {
    ...
}

Choose whichever pattern makes sense to you. More to the point, choose the pattern that makes sense to your future self when you revisit your code.

Feature queries need to work together with media queries. Sometimes there are effects that you only want to apply on larger viewports. Do you put your feature queries inside your media queries? Or do you put your media queries inside your feature queries?

  • MOSS: Media Outside Support Statements
  • MISO: Media Inside Supports Object

Use MOSS when you have more media switches than support blocks. Use MISO when you only have a few breakpoints but lots of feature queries.

That’s one idea that Eric has. It’ll be interesting to see how this develops.

And remember, CSS is still CSS. Sometimes you don’t need a feature query at all. You could just use hanging-punctuation without testing for it. Browsers that don’t understand it will just ignore it. CSS has implicit feature queries built in. You don’t have to put your grid layout in a feature query, but you might want to put grid-specific margins and widths inside a feature query for display: grid.

Feature queries really help us get from now to the future.

Flexbox

Let’s move on to flexbox. Flexbox is great for things in a line.

On the An Event Apart site, the profile pictures have social media icons lined up at the bottom. Sometimes there are just a few. Sometimes there are a lot more. This is using flexbox. Why? Because it’s cool. Also, because it’s flexbox, you can create rules about how the icons should behave if one of the icons is taller than the others. (It’s gotten to the point that Eric has forgotten that vertically-centring things in CSS is supposed to be hard. The jokes aren’t funny any more.) Also, what if there’s no photo? Using flexbox, you can say “if there’s no photo, change the direction of the icons to be vertical.” Once again, it’s all about writing less CSS.

Also, note that the profile picture is being floated. That’s the right tool for the job. It feels almost transgressive to use float for exactly the purpose for which it was intended.

On the An Event Apart site, the header is currently using absolute positioning to pull the navigation from the bottom of the page source to the top of the viewport. But now you get overlap at some screen sizes. Flexbox would make it much more robust. (Eric uses the flexbox inspector in Firefox Nightly to demonstrate.)

With flexbox, what works horizontally works vertically. Flexbox allows you to align things, as long as you’re aligning in one direction. Flexbox makes things springy. Everything’s related and pushing against each other in a way that makes sense for this medium. It’s intuitive, even though it takes a bit of getting used to …because we’ve picked up some bad habits. To quote Yoda, “You must unlearn what you have learned.” A lot of the barrier is getting over what we’ve internalised. Eric envies the people starting out now. They get to start fresh. It’s like when people who never had to table layouts see code from that time period: it (quite rightly) doesn’t make any sense. That’s what it’s going to be like when people starting out today see the float-based layouts from Bootstrap and the like.

Grid

That’s going to happen with grid too. We must unlearn what we have learned from twenty years of floats and positioning. What makes it worth is:

  1. Flexbox and grid are pretty easy to get used to, and
  2. It’s amazing what you can do!

Eric quotes from an article called How We adopted CSS Grid at Scale:

…we agreed to use CSS Grid at the layout level and Flexbox at the component level (arranging child items of components). Although there’s some overlap and in some cases both could be used interchangeably, abiding by this rule helped us avoid any confusion in gray areas.

Don’t be afraid to set these kind of arbitrary limits that aren’t technological, but are necessary for the team to work well together.

Eric hacked his Wordpress admin interface to use grid instead of floats for an activity component (a list of dates and titles). He initially turned each list item into a separate grid. The overall list didn’t look right. What Eric really needed was a subgrid capability, so that the mini grids (the list items) would relate to one another within the larger grid (the list). But subgrid doesn’t exist yet.

In this case, there’s a way to fake it using display: contents. Eric made the list a grid and used display: contents on the list items. It’s as though you’re saying that the contents of the li are really the contents of the ul. That works in this particular case.

The feature queries for that looked like:

@supports (display: grid) {
    ...
    @supports (display: contents) {
        ...
    }
}

Eric is also using the grid “ASCII art” (named areas) technique on his personal site. This works independent of source order. For that reason, make sure your source order makes sense.

Using media queries, Eric defines entirely different layouts simply by using different ASCII art. He’s switching templates.

For a proposed redesign of the An Event Apart site, Eric used CSS grid as a prototyping tool. He took a PDF, sliced it up, exported JPGs, and then used grid to lay out those images in a flexible grid. Rapid prototyping! The Firefox grid inspector really helps here. In less than an hour, he had a working layout. He could test whether the layout was sensible and robust. Then he swapped out the sliced images for real content. That took maybe another hour (mostly because it was faster to re-type the text than try to copy and paste from a PDF). CSS makes it that damn easy now!

So even if you’re not going to put things like grid into production, they can still be enormously useful as design tools (and you’re getting to grips with this new stuff).

See also:

Graduating to Grid by Rachel Andrew

It’s time for a gridtastic afternoon at An Event Apart Seattle (Special Edition). Kicking it off is Rachel with her talk Graduating to Grid. Here are my notes…

When Rachel spoke at An Event Apart last year, grid layout was still on the horizon. Then in March 2017, Chrome, Safari, and Firefox all shipped within weeks of one another. Then at An Event Apart Seattle last year, Edge announced that they were shipping too. So within a very short time, CSS grid got really good browser support.

What’s it like being in the middle of a launch of a big new CSS feature? Very quickly, we had 90% browser support. Suddenly it wasn’t just Jen and Rachel talking about grid—everyone was talking about grid. It involved a lot of email. Alas, Rachel couldn’t answer all those questions (she has a job, after all) but she did start collecting those questions. She found that people were excited, confused, and scared. So much to learn!

Rachel put out a survey and asked “How do you feel when a new CSS feature is announced?” Responses included “Oh, no!” and “Tired.” Some of us in the audience can, no doubt, identify with that.

People started emailing Rachel asking for her blessing. Were they doing the right thing? But Rachel can’t tell you what to do. She’s not in your situation. But she can help you develop the skills to make those decisions yourself. She can offer you confidence. She wants everyone to be the amazing CSS layout person on their team. That’s what this talk is for.

First of all, you need to understand CSS. There’s no shortcut here. But that doesn’t mean you need to learn every single property and value by heart. That’s not what CSS is about. That’s like learning phrases in a foreign language—knowing the words for “coffee” or “beer” doesn’t help you grok the language. It’s the same for CSS. There are some core ideas that help CSS layout make sense. You probably have an understanding of them already, but maybe you don’t have the right words for them.

At the heart of this is the first word in the language we’re talking about: cascading. You need to understand the (much-maligned) cascade. And you can’t talk about the cascade without encountering specificity. The MDN page on the cascade and specificity is a good explanation.

Then there’s dimensions. In any language with a horizontal writing mode, the inline dimension runs left to right or right to left, and the block dimension runs down the page from top to bottom. In vertical writing mode, it’s different.

In grid, we talk about the inline axis as rows, and the block axis as columns.

Sizing matters. It has become obvious that no one understands how big anything is. We’re living in a world where you don’t control the size of things.

In older float-based systems, everything is given a percentage. As long as our percentages don’t exceed 100%, everything’s okay. And we’ve got wrappers to keep things within rows. We end up with something that looks like a grid. It involves us doing a lot of calculating. You can do this with flexbox too, but it’s much the same—figuring out percentages. These past layout methods create the appearance of a grid by lining things up.

With the new layout, we don’t have to do the calculations. We need to understand CSS intrinsic sizing and extrinsic sizing (say that ten times fast).

With a regular div, you’ve got a block-level element. The box will stretch as far as it will go, to the viewport width by default. You can specify an intrinsic size by saying, say, width: 500px. That makes 500 pixels wide in the inline direction.

However the content of the box has a size. The maximum size of a string of text is how much space it would take up if it never wrapped. The minimum size is the space it would take up if everything wrapped. Now in CSS we can say width: min-content or width: max-content.

Let’s say our div was in a container that had a width of 20em. The max-content of the contents of the div (which is more than 20 ems) is wider than the width of the div and so the content overflows.

In flexbox, let’s say we’ve got a flex container with four items and we’ve declared that each one should take up max-content. Each item takes up as much space as it needs. Each one uses max-content as its starting point, and then width is removed to make all four items fit in the container. flex: 1 1 auto will distribute space according to the content. flex: 1 1 0 will distribute the space equally (you’re effectively saying that the max-content is zero).

It’s similar with grid layout but with slight differences. Flexbox is starting from max-content and taking space away. Grid is starting from min-content and adding space.

Those content keywords aren’t well supported outside grid layout. They’re safe to use for track sizing.

grid-template-columns: repeat(4, min-content);

That will make everything squished down.

grid-template-columns: repeat(4, max-content);

That one will probably cause an overflow.

grid-template-columns: repeat(4, fit-content(15ch));

That one will make 15 characters an upper limit!

You can make a grid layout using fr units and grid-gap. No need for figuring out percentages. You can use percentages if you like though. You can use percentages for gaps, for example.

Remember, you don’t have to stick with a twelve column grid. Slack started with that because it was what they were used to. Then they realised they didn’t have to.

Imagine a media object pattern, where you don’t want the image to ever be bigger than 300 pixels.

grid-template-columns: fit-content(300px) 1fr

As Rachel creates more layouts with grid, she finds she’s using less and less CSS, which is great. The browser is doing the work. That matches the reality of the situation where you don’t know the size of your content in advance—long titles, and so on.

This is not exciting. But it will let you do exciting things. Learning about sizing is the CSS equivalent of eating your vegetables or getting enough sleep.

“Why is all of this so complicated?”, is something Rachel hears a lot. It’s like all software. People want all the features, and they also want it to be easy to use.

More capability and flexibility means more to learn. But it’s worth remembering that you don’t have to learn everything at once. Once you switch your mindset to the grid way of thinking (where you define things on the layout) it gets easier. It’s all just lines.

If you name your grid lines, e.g. “content-start” and “content-end”, you automatically get a named area called “content.”

It works the other way around too. If you create an area called “content”, you automatically get lines named “content-start” and “content-end”.

You don’t have to use any of that. You have real choice for the first time.

A lot of the assumptions we’ve had in the past about what isn’t possible don’t hold up any more. You can now ask, “what’s the best way to do this?” instead of asking “which patterns does our framework give us?”

Well, that’s fine, you might be thinking, for shiny new things. But what if you’re building things that have an old codebase? Rachel asked “How old is the oldest CSS in your project?” in her survey. People have code that’s over ten years old. But old CSS in your codebase doesn’t mean you can’t use new CSS. You can design components or a section of a page using a new technique. This is where understanding CSS comes in really useful—the cascade, especially.

Rachel shows an example of a page made with Bootstrap. She drops a grid component into that layout. It works fine. Nothing explodes. They coexist side by side.

You can create systems with new layout. You’ve got a lot of choice. You can start to make decisions about which layout method works best for different situation. Other layout methods still exist. Don’t try to recreate floats within grid—just use floats. It’s like when we moved from tables for layout, some people went too far and stopped using tables for tabular data. If you need content to flow around an element, float that element. Likewise, if you’re doing layout in just one dimension, you don’t have to use grid; use flexbox.

Off-the-shelf frameworks are designed to solve generic problems. We end up solving problems we don’t have. Do you want your project to inherit the CSS problems of the rest of the world? Solving your specific problems only will result in lighter, easier to understand code.

You don’t need to lean on somebody else’s framework to get reusable code for your project and your team.

What about working with less capable browsers? (these may not always be old browsers). Let’s go back to 2006 and Yahoo’s graded browser support matrix. It was updated quarterly. It was useful. A lot of discussion around browser support was happening with a lack of understanding on one side (bosses, clients) meeting a lack of confidence on the other (developers). Yahoo’s browser support matrix gave us ammunition. If it was okay for Yahoo to say that it was okay for certain browsers to not receive certain features, then that argument was easier to make.

A lot of the discussion now is about older Internet Explorer—IE11 comes up a lot. If IE10 and 11 are your oldest supported versions, you can use the ms- prefixed grid layout.

Some people are using devices that aren’t updating to new browsers. UC browser for Android is used a lot. It’s very popular in India (35% usage). Many browsers without grid support are mobile browsers, popular in areas where data is expensive.

People want a magical grid polyfill that will make grid work in non-supporting browsers. Please stop asking for that! Why, oh, why would you send more JavaScript to less-capable devices!

You can use feature queries to ask if a browser supports a feature before using it. The great thing about doing this is that you are future-proofing: as browsers get support for features, your code works automatically.

You can create complex layouts for browsers that support them with a few lines of CSS. Being able to do new cool stuff is great. Saving developer time is great. But making the web available to everyone …that’s exciting!

To wrap up, Rachel recounts some of the other responses to her survey. People said they were “Excited!”

See also:

Styling the Patterns Day site

Once I had a design direction for the Patterns Day site, I started combining my marked-up content with some CSS. Ironically for an event that’s all about maintainability and reusability, I wrote the styles for this one-page site with no mind for future use. I treated the page as a one-shot document. I even used ID selectors—gasp! (the IDs were in the HTML anyway as fragment identifiers).

The truth is I didn’t have much of a plan. I just started hacking away in a style element in the head of the document, playing around with colour, typography, and layout.

I started with the small-screen styles. That wasn’t a conscious decision so much as just the way I do things automatically now. When it came time to add some layout for wider viewports, I used a sprinkling of old-fashioned display: inline-block so that things looked so-so. I knew I wanted to play around with Grid layout so the inline-block styles were there as fallback for non-supporting browsers. Once things looked good enough, the fun really started.

I was building the site while I was in Seattle for An Event Apart. CSS Grid layout was definitely a hot topic there. Best of all, I was surrounded by experts: Jen, Rachel, and Eric. It was the perfect environment for me to dip my toes into the waters of grid.

Jen was very patient in talking me through the concepts, syntax, and tools for using CSS grids. Top tip: open Firefox’s inspector, select the element with the display:grid declaration, and click the “waffle” icon—instant grid overlay!

For the header of the Patterns Day site, I started by using named areas. That’s the ASCII-art approach. I got my head around it and it worked okay, but it didn’t give me quite the precision I wanted. I switched over to using explicit grid-row and grid-column declarations.

It’s definitely a new way of thinking about layout: first you define the grid, then you place the items on it (rather than previous CSS layout systems where each element interacted with the elements before and after). It was fun to move things around and not have to worry about the source order of the elements …as long as they were direct children of the element with display:grid applied.

Without any support for sub-grids, I ended up having to nest two separate grids within one another. The logo is a grid parent, which is inside the header, also a grid parent. I managed to get things to line up okay, but I think this might be a good use case for sub-grids.

The logo grid threw up some interesting challenges. I wanted each letter of the words “Patterns Day” to be styleable, but CSS doesn’t give us any way to target individual letters other than :first-letter. I wrapped each letter in a b element, made sure that they were all wrapped in an element with an aria-hidden attribute (so that the letters wouldn’t be spelled out), and then wrapped that in an element with an aria-label of “Patterns Day.” Now I could target those b elements.

For a while, I also had a br element (between “Patterns” and “Day”). That created some interesting side effects. If a br element becomes a grid item, it starts to behave very oddly: you can apply certain styles but not others. Jen and Eric then started to test other interesting elements, like hr. There was much funkiness and gnashing of specs.

It was a total nerdfest, and I loved every minute of it. This is definitely the most excitement I’ve felt around CSS for a while. It feels like a renaissance of zen gardens and layout reservoirs (kids, ask your parents).

After a couple of days playing around with grid, I had the Patterns Day site looking decent enough to launch. I dabbled with some other fun CSS stuff in there too, like gratuitous clip paths and filters when hovering over the speaker images, and applying shape-outside with an image mask.

Go ahead and view source on the Patterns Day page if you want—I ended up keeping all the CSS in the head of the document. That turned out to be pretty good for performance …for first-time visits anyway. But after launching the site, I couldn’t resist applying some more performance tweaks.

Getting griddy with it

I had the great pleasure of attending An Event Apart Seattle last week. It was, as always, excellent.

It’s always interesting to see themes emerge during an event, especially when those thematic overlaps haven’t been planned in advance. Jen noticed this one:

I remember that being a theme at An Event Apart San Francisco too, when it seemed like every speaker had words to say about ill-judged use of Bootstrap. That theme was certainly in my presentation when I talked about “the fallacy of assumed competency”:

  1. large company X uses technology Y,
  2. company X must know what they are doing because they are large,
  3. therefore technology Y must be good.

Perhaps “the fallacy of assumed suitability” would be a better term. Heydon calls it “the ‘made at Facebook’ fallacy.” But I also made sure to contrast it with the opposite extreme: “Not Invented Here syndrome”.

As well as over-arching themes, it was also interesting to see which technologies were hot topics at An Event Apart. There was one clear winner here—CSS Grid Layout.

Microsoft—a sponsor of the event—used An Event Apart as the place to announce that Grid is officially moving into development for Edge. Jen talked about Grid (of course). Rachel talked about Grid (of course). And while Eric and Una didn’t talk about it on stage, they’ve both been writing about the fun they’ve been having having with Grid. Una wrote about 3 CSS Grid Features That Make My Heart Flutter. Eric is documenting the overall of his site with Grid. So when we were all gathered together, that’s what we were nerding out about.

The CSS Squad.

There are some great resources out there for levelling up in Grid-fu:

With Jen’s help, I’ve been playing with CSS Grid on a little site that I’m planning to launch tomorrow (he said, foreshadowingly). I took me a while to get my head around it, but once it clicked I started to have a lot of fun. “Fun” seems to be the overall feeling around this technology. There’s something infectious about the excitement and enthusiasm that’s returning to the world of layout on the web. And now that the browser support is great pretty much across the board, we can start putting that fun into production.

Vertical limit

When I was first styling Resilient Web Design, I made heavy use of vh units. The vertical spacing between elements—headings, paragraphs, images—was all proportional to the overall viewport height. It looked great!

Then I tested it on real devices.

Here’s the problem: when a page loads up in a mobile browser—like, say, Chrome on an Android device—the URL bar is at the top of the screen. The height of that piece of the browser interface isn’t taken into account for the viewport height. That makes sense: the viewport height is the amount of screen real estate available for the content. The content doesn’t extend into the URL bar, therefore the height of the URL bar shouldn’t be part of the viewport height.

But then if you start scrolling down, the URL bar scrolls away off the top of the screen. So now it’s behaving as though it is part of the content rather than part of the browser interface. At this point, the value of the viewport height changes: now it’s the previous value plus the height of the URL bar that was previously there but which has now disappeared.

I totally understand why the URL bar is squirrelled away once the user starts scrolling—it frees up some valuable vertical space. But because that necessarily means recalculating the viewport height, it effectively makes the vh unit in CSS very, very limited in scope.

In my initial implementation of Resilient Web Design, the one where I was styling almost everything with vh, the site was unusable. Every time you started scrolling, things would jump around. I had to go back to the drawing board and remove almost all instances of vh from the styles.

I’ve left it in for one use case and I think it’s the most common use of vh: making an element take up exactly the height of the viewport. The front page of the web book uses min-height: 100vh for the title.

Scrolling.

But as soon as you scroll down from there, that element changes height. The content below it suddenly moves.

Let’s say the overall height of the browser window is 600 pixels, of which 50 pixels are taken up by the URL bar. When the page loads, 100vh is 550 pixels. But as soon as you scroll down and the URL bar floats away, the value of 100vh becomes 600 pixels.

(This also causes problems if you’re using vertical media queries. If you choose the wrong vertical breakpoint, then the media query won’t kick in when the page loads but will kick in once the user starts scrolling …or vice-versa.)

There’s a mixed message here. On the one hand, the browser is declaring that the URL bar is part of its interface; that the space is off-limits for content. But then, once scrolling starts, that is invalidated. Now the URL bar is behaving as though it is part of the content scrolling off the top of the viewport.

The result of this messiness is that the vh unit is practically useless for real-world situations with real-world devices. It works great for desktop browsers if you’re grabbing the browser window and resizing, but that’s not exactly a common scenario for anyone other than web developers.

I’m sure there’s a way of solving it with JavaScript but that feels like using an atomic bomb to crack a walnut—the whole point of having this in CSS is that we don’t need to use JavaScript for something related to styling.

It’s such a shame. A piece of CSS that’s great in theory, and is really well supported, just falls apart where it matters most.

Update: There’s a two-year old bug report on this for Chrome, and it looks like it might actually get fixed in February.

Strong Layout Systems by Eric Meyer

Eric is at An Event Apart in Atlanta talking about Strong Layout Systems. Following on from Brother Jeffrey’s presentation, he begins with a reading…

In the beginning Sir Tim created the server and the browser. And the web was without form. And the face of Tim moved over the web. Tim said “Let there be markup.” And there was markup. And he saw that it was good. And he divided structure from appearance.

That decision is quite striking. Think about other mediums. The structure of a book is bound to its appearance.

Here’s a screenshot, courtesy of Grant Hutchinson, of the preferences in the original Mosaic browser. You could define the appearance of any HTML element …as a user. As an author, you couldn’t do that. HTML didn’t support that: it created structure.

As with all creations, there was a fall. As usual, a reptile was involved. In this case it was Mozilla, known by its ancient name of Netscape. They added presentational elements like prompt and presentational attributes e.g. on the hr element. And then there was the table element. Inevitably, it was used for layout. David Siegel wrote the book on this, Creating Killer Websites. It was tables all the way down: tables inside of tables inside of tables, all to create visual appearance.

The backlash came from the Web Standards Project. It got dogmatic there for a while. But we got past that, and we started using CSS. The promise of CSS was visual presentation, for authors and users. We talk about “controlling” presentation with CSS, but remember that theoretically that can be over-ridden by user styles.

But CSS was an appearance system; not a layout system. It wasn’t that complex. You could print out all of CSS1. The only thing in it in any way suited for layout was floats …and that’s not what they were created for: it was basically the CSS equivalent of the align attribute that Netscape had introduced to HTML. So we used floats because that’s all we had. It wasn’t a layout system but we made it one anyway. There were a lot of bugs, but we dealt them in clever—sometimes deranged—ways.

For CSS2, they realised that designers really liked to lay things out (who knew?) so they introduced positioning. But you have to be careful with positioning. It was great …sort of. You can indeed position an element wherever you want …and overlap them.

The first major site to launch with CSS for positioning was Doug’s redesign of Wired.com (it didn’t use floats). The limitations of positioning forced us into certain design patterns. Note the footer on the old Wired site: it sits at the bottom of the central column, not the whole page. That was to avoid overlap. But Eric remembers talking to Doug and it turns out they actually wanted a full-width footer, but they had to work with the tools they had. Positioning lacked the equivalent of clear that you get with floats.

These were hacks. Hacks aren’t a bad thing; they’re often very clever. But hacks limit us. Neither floats nor positioning had the concept of equal height (but tables did).

We’re now getting to the point where can start to revisit our assumptions about what is and isn’t possible with CSS.

We’ve got viewport units: vh and vw—viewport height and viewport width (in percentages relative to the viewport, not the parent element). This is really useful for handheld devices. There’s also the vmin unit that you can use on font sizes so that text scales in relation to viewport size.

Flexible boxes is more commonly called flexbox. Take a horizontal navigation (in an unordered list) and declare it as a flexible box. Then declare that the elements within should “flex” to each use an equal amount of space. There’s a variant justify-content: space-around which will share out the space between the elements equally.

Flexbox comes out of XUL, Gecko’s layout language for browser chrome. This is real layout. It’s not a hack. As an author, you’re declaring how you want things to be laid out, and the browser does it. It’s a good feeling.

You can also use flexbox to make sure that elements within a shared parent have the same height. In fact, that’s the default behaviour. You can also get your flexible boxes to reflow instead of being trapped on the same line. The new “line” will also share out space for the elements equally.

You can set your flexible boxes with whatever units you want, and mix and match them: percentages and ems, for example. You can have flexible and fixed elements together.

Remember The Holy Grail of Layout on A List Apart? It followed soon after the One True Layout. Now you could do it with just a few quick flexbox declarations.

<header></header>
<main>
 <nav></nav>
 <article></article>
 <aside></aside>
</main>
<footer></footer>

main { display: flex; }
nav { width: 13em; flex: none; }
article { width: auto; flex: none; }
aside { width: 20%; flex: none; }

You can also rearrange the visual ordering (using order). You could make the article appear as the third column within main even though it appears second in the markup. The structure is truly separated from the layout.

Flexbox alignments are really interesting, especially baseline, which will vertically align columns according to the first baseline in each column — very handy.

You aren’t restricted to horizontal layout: you can arrange things vertically. We finally get vertical centring.

Beyond flexbox, we have grids. They’re not quite as stable right now, but the basic idea is that you can set up grid lines to “control” page elements and the space between them: grid-definition-columns: (4em) gives you a repeating grid with a grid unit of four ems.

You can have flexbox inside grids and visa-versa: within a grid unit, you can still display: flex. Within a flexible box, you can define grid lines.

But please don’t go and read the grids specification right now. It’s an amalgamation of three different authors’ texts, one of whom has never written a spec before, and one of the examples is completely misleading about how grids work.

There’s a fraction unit—fr—that you can use to define widths, but you can also use it in combination with min-content which is based on the longest piece of content in a unit. This is complicated stuff and even Eric doesn’t quite get it completely. Maybe min-content is better for non-text content.

And remember you can mix and match these modules. Same with CSS regions. Regions aren’t here yet, but they will completely up-end the way we think about document structure: you put all of your content in one element, and you have some empty elements as well. Then you use CSS regions to define how the content from the first element flows into the others. Effectively your document has a structural portion and a skeleton layout portion.

These layout modules are truly new. You might think that we’re familiar with using CSS for layout, but that was always hacking: using tools for a purpose other than that for which they were created. This new modules were created specifically to allow us to create layouts. That really is new. And Eric can’t wait to see what we do with these new tools.

Tweakpoints

Mark has written down some thoughts on breakpoints in responsive designs. I share his concern that by settling on just a few breakpoints, there’s a danger of returning to the process of simply designing for some set canvases: here’s my “mobile” layout, here’s my “tablet” layout, here’s my “desktop” layout.

In my experience, not all breakpoints are created equal. Sure, there are the points at which the layout needs to change drastically in order for the content not to look like crap—those media queries can legitimately be called breakpoints. But then there are the media queries that are used to finesse page elements without making any major changes to the layout.

When I was working on Matter, for example, there was really only one major breakpoint, where the layout shifts from one column to two. That’s the kind of breakpoint that you can figure out pretty easily from the flow of your content; just resizing your browser window is usually enough to settle on the point that feels right. But there are lots of other media queries in the Matter stylesheet. Those are there to make smaller adjustments to margins, font sizes …the kind of changes that came about from testing on phones and tablets in the device lab.

It feels a bit odd to call them breakpoints, as though the layout would “break” without them. Those media queries are there to tweak the layout. They’re not breakpoints; they’re tweakpoints.

Media queries and multiple columns

By far the most common use of media queries is to execute CSS based on viewport width (using min-width or max-width). Lately there’s been more talk about using media queries based on height as well.

Paul talked about using min-height media queries to adjust content appearing above the fold. Owen Gregory wrote his superb 24 Ways article on using viewport proportions and device-aspect-ratio for media queries. Trent has documented his use of horizontal and vertical media queries to bump up the font size for wide and tall viewports.

One of the areas where I’ve found height-based media queries to be quite handy is in combination with another CSS3 module: multiple columns.

Splitting text over multiple columns is not something to be done lightly on a screen-based display. If the columns drop below the viewport then the user has to scroll down, scroll back up, scroll down again …you get the picture. It works fine in print but it’s not something that should be attempted on the web unless the entire text is visible at one time.

Well, with media queries we can get a pretty good idea of whether the text will fit on the viewport …assuming we know the length of the text.

Here’s an example (thanks to Space Ipsum for supplying the text). It splits the text into two columns if the viewport has enough width and height:

@media all and (min-width: 40em) and (min-height: 36em) {
    [role="main"] {
        column-count: 2;
        column-gap: 2em;
    }
}

If the viewport is wider still, the text can be split over three columns. In this case, the test for height can actually smaller because the text is spreading over a wider area, meaning the overall height of the text is shorter:

@media all and (min-width: 65em) and (min-height: 25em) {
    [role="main"] {
        column-count: 3;
        column-gap: 2em;
    }
}

The actual CSS is more verbose than that: vendor prefixes are still required. You can grab the example from Github if you want to have a play around with it.