Journal tags: styles

17

Making the Patterns Day website

I had a lot of fun making the website for Patterns Day.

If you’re interested in the tech stack, here’s what I used:

  1. HTML
  2. CSS

Actually, technically it’s all HTML because the styles are inside a style element rather than a separate style sheet, but you know what I mean. Also, there is technically some JavaScript but all it does is register a service worker that takes care of caching and going offline.

I didn’t use any build tools. There was no pipeline. There is no node_modules folder filling up my hard drive. Nothing was automated. The website was hand-crafted the long hard stupid way.

I started with the content. I wrote out the words and marked them up with the most appropriate HTML elements.

A screenshot of an unstyled web page for Patterns Day.

Time to layer on the presentation.

For the design, I turned to Michelle for help. I gave her a brief, describing the vibe of the conference, and asked her to come up with an appropriate visual language.

Crucially, I asked her not to design a website. Instead I asked her to think about other places where this design language might be used: a poster, social media, anything but a website.

Partly I was doing this for my own benefit. If you give me a pixel-perfect design for a web page and tell me to code it up, either I won’t do it or I won’t enjoy it. I just don’t get any motivation out of that kind of direct one-to-one translation.

But give me guardrails, give me constraints, give me boundary conditions, and off I go!

Michelle was very gracious in dealing with such a finicky client as myself (“Can you try this other direction?”, “Hmm… I think I preferred the first one after all!”) She delivered a colour palette, a type scale, typeface choices, and some wonderful tiling patterns …it is Patterns Day after all!

With just a few extra lines of CSS, the basic typography was in place.

A screenshot of the web page for Patterns Day with web fonts applied.

I started layering on the colours. Even though this was a one-page site, I still made liberal use of custom properties in the CSS. It just feels good to be able to update one value and see the results, well …cascade.

A screenshot of the web page for Patterns Day with colours added.

I had a lot of fun with the tiling background images. SVG was the perfect format for these. And because the tiles were so small in file size, I just inlined them straight into the CSS.

By this point, I felt like I was truly designing in the browser. Adjusting spacing, playing around with layout, and all that squishy stuff. Some of the best results came from happy accidents—the way that certain elements behaved at certain screen sizes would lead me into little experiments that yielded interesting results.

I’m not sure it’s possible to engineer that kind of serendipity in Figma. Figma was the perfect tool for exploring ideas around the visual vocabulary, and for handing over design decisions around colour, typography, and texture. But when it comes to how the content is going to behave on the World Wide Web, nothing beats a browser for fidelity.

A screenshot of the web page for Patterns Day with some changes applied.

By this point I was really sweating the details, like getting the logo just right and adjusting the type scale for different screen sizes. Needless to say, Utopia was a godsend for that.

I was also checking back in with Michelle to get her take on design decisions I was making.

I could’ve kept tinkering but the diminishing returns were a sign that it was time to put this out into the world.

A screenshot of the web page for Patterns Day with the logo in place.

It felt really good to work on a web page like this. It felt like I was getting my hands into the soil of the web. I don’t think it’s an accident that the result turned out to be very performant.

Getting hands-on like this stops me from getting rusty. And honestly, working with CSS these days is a joy. There’s such power to be had from using var() in combination with functions like calc() and clamp(). Layout is a breeze with flexbox and grid. Browser differences are practically non-existent. We’ve never had it so good.

Here’s something I noticed about my relationship to CSS; my brain has finally made the switch to logical properties. Now if I’m looking at some CSS and I see left, right, top, or bottom, it looks like a bug to me. Those directional properties feel loaded with assumptions whereas logical properties feel much more like working with the grain of the web.

Culture and style

Ever get the urge to style a good document?

No? Just me, then.

Well, the urge came over me recently so I started styling this single-page site:

A Few Notes On The Culture by Iain M Banks

I’ve followed this document across multiple locations over the years. It started life as a newsgroup post on rec.arts.sf.written in 1994. Ken McLeod published it there on Iain M Banks’s behalf.

The post complements the epic series of space opera books that Iain M Banks set in the anarcho-utopian society of The Culture. It’s a fascinating piece of world building, as well as an insight into the author’s mind.

I first became aware of it many few years later, after a copy had been posted to the web. That URL died, but Adrian Hon kept a copy on his site. Lots of copies keep stuff safe, so after contemplating linkrot, I made a copy on this site too.

But I recently thought that maybe it deserved a bit of art direction, so I rolled up my sleeves and started messing around, designing in the browser and following happy little accidents.

The finished result is still fairly sparse. It’s still entirely text, except for a background image that shows up if your screen is wide enough. That image of a planet originally started as an infra-red snapshot of Jupiter by the James Webb Space Telescope that I worked over until it was unrecognisable.

The text itself is the main focus of the design though. I knew I wanted to play around with a variable font. Mona Sans from Github was one of the first ones I tried and I found it instantly suitable. I had a lot of fun playing with different weights and widths.

After a bit of messing around, I realised that the heading styles were reminding me of some later reissues of The Culture novels, so I leant into that, deliberately styling the byline to resemble the treatment of the author’s name on those book covers.

There isn’t all that much CSS. I’ve embedded it in the head of the HTML rather than linking to a separate style sheet, so feel free to view source and poke around in there. You’ll see that I’m making liberal use of custom properties, the clamp function, and logical properties.

Originally I had a light mode and dark mode but I found that the dark mode was much more effective so I ditched the lighter option.

I did make sure to include some judicious styles for print, so if you fancy reading on paper, it should print out nicely.

Oh, and of course it’s a progressive web app that works offline.

I didn’t want to mess with the original document other than making some typographic tweaks to punctuation, but I wanted to break up the single wall of text. I wasn’t about to start using pull quotes on the web so in the end I decided to introduce some headings that weren’t in the original document:

  1. Government
  2. Economics
  3. Technology
  4. Philosophy
  5. Lifestyle
  6. Travel
  7. Habitat
  8. Legal System
  9. Politics
  10. Identity
  11. Nomenclature
  12. Cosmology

If your browser viewport is tall enough, the heading for the current section you’re reading will remain sticky as you scroll. No JavaScript required.

I’m pretty pleased with how this little project turned out. It was certainly fun to experiment with fluid type and a nice variable font.

I can add this to my little collection of single-page websites I’ve whittled over the years:

Alternative stylesheets

My website has different themes you can choose from. I don’t just mean a dark mode. These themes all look very different from one another.

I assume that 99.99% of people just see the default theme, but I keep the others around anyway. Offering different themes was originally intended as a way of showcasing the power of CSS, and specifically the separation of concerns between structure and presentation. I started doing this before the CSS Zen Garden was created. Dave really took it to the next level by showing how the same HTML document could be styled in an infinite number of ways.

Each theme has its own stylesheet. I’ve got a very simple little style switcher on every page of my site. Selecting a different theme triggers a page refresh with the new styles applied and sets a cookie to remember your preference.

I also list out the available stylesheets in the head of every page using link elements that have rel values of alternate and stylesheet together. Each link element also has a title attribute with the name of the theme. That’s the standard way to specify alternative stylesheets.

In Firefox you can switch between the specified stylesheets from the View menu by selecting Page Style (notice that there’s also a No style option—very handy for checking your document structure).

Other browsers like Chrome and Safari don’t do anything with the alternative stylesheets. But they don’t ignore them.

Every browser makes a network request for each alternative stylesheet. The request is non-blocking and seems to be low priority, which is good, but I’m somewhat perplexed by the network request being made at all.

I get why Firefox is requesting those stylesheets. It’s similar to requesting a print stylesheet. Even if the network were to drop, you still want those styles available to the user.

But I can’t think of any reason why Chrome or Safari would download the alternative stylesheets.

Stakeholders of styling

When I wrote about the new accent-color property in CSS, I pondered how much control a web developer should have over styling form controls:

Who are we to make that decision? Shouldn’t the user’s choice take primacy over our choices?

But then again, where do we draw the line? We’re allowed over-ride link colours. We’re allowed over-ride font choices.

Ultimately, I came down on the side of granting authors more control:

If developers don’t get a standardised way to customise native form controls, they’ll just recreate their own over-engineered versions.

This question of “who gets to decide?” used to be much more prevelant in the early days of the web. One way to think about this is that there are three stakeholders involved in the presentation of a web page:

  1. The author of the page. “Author” is spec-speak for designer or developer.
  2. The user.
  3. The browser, or user agent. A piece of software tries to balance the needs of both author and user. But, as the name implies, the user takes precedence.

These days we tend to think of web design a single-stakeholder undertaking. The author decides how something should be presented and then executes that decision using CSS.

But as Eric once said, every line of you CSS you write is a suggestion to the browser. That’s not how we think about CSS though. We think of CSS like a series of instructions rather than suggestions. Never mind respecting the user’s preferences; one of the first things we do is reset all the user agent’s styles.

In the early days of the web, more consideration was given to the idea of style suggestions rather than instructions. Heck, users could always over-ride any of your suggestions with their own user stylesheet. These days, users would need to install a browser extension to do the same thing.

The first proposal for CSS had a concept called “influence”:

h2.font.size = 20pt 40%

Here, the requested influence is reduced to 40%. If a style sheet later in the cascade also requests influence over h2.font.size, up to 60% can be granted. When the document is rendered, a weighted average of the two requests is calculated, and the final font size is determined.

I think the only remnant of “influence” left in CSS is accidental. It’s in the specificity of selectors …and the !important declaration.

I think it’s a shame that user stylesheets are no longer a thing. But I get why they were dropped from browsers. They date from a time when it was mostly nerds using the web, before “regular folks” came on board. I understand why it became a little-used feature, suitable for being dropped. But the principle of it still rankles slightly.

But in recent years there has been a slight return to the multi-stakeholder concept of styling websites. Thanks to prefers-reduced-motion and prefers-color-scheme, a responsible author can choose to bow to the wishes of the user.

I was reminded of this when I added a dark mode to my website:

Y’know, when I first heard about Apple adding dark mode to their OS—and also to CSS—I thought, “Oh, great, Apple are making shit up again!” But then I realised that, like user style sheets, this is one more reminder to designers and developers that they don’t get the last word—users do.

SVGs in dark mode

I added a dark mode to my site last year. Since then I’ve been idly toying with the addition of a dark mode to The Session too.

As with this site, the key to adding a dark mode was switching to custom properties for color and background-color declarations. But my plans kept getting derailed by the sheet music on the site. The sheet music is delivered as SVG generated by ABCJS which hard-codes the colour in stroke and fill attributes:

fill="#000000" stroke="#000000"

When I was describing CSS recently I mentioned the high specifity of inline styles:

Whereas external CSS and embedded CSS don’t have any effect on specificity, inline styles are positively radioactive with specificity.

Given that harsh fact of life, I figured it would be nigh-on impossible to over-ride the colour of the sheetmusic. But then I realised I was an idiot.

The stroke and fill attributes in SVG are presentational but they aren’t inline styles. They’re attributes. They have no affect on specifity. I can easily over-ride them in an external style sheet.

In fact, if I had actually remembered what I wrote when I was adding a dark mode to adactio.com, I could’ve saved myself some time:

I have SVGs of sparklines on my homepage. The SVG has a hard-coded colour value in the stroke attribute of the path element that draws the sparkline. Fortunately, this can be over-ridden in the style sheet:

svg.activity-sparkline path {
  stroke: var(--text-color);
}

I was able to do something similar on The Session. I used the handy currentColor keyword in CSS so that the sheet music matched the colour of the text:

svg path {
  fill: currentColor;
}
svg path:not(stroke="none") {
  stroke: currentColor;
}

Et voila! I now had light-on-dark sheet music for The Session’s dark mode all wrapped up in a prefers-color-scheme: dark media query.

I pushed out out the new feature and started getting feedback. It could be best summarised as “Thanks. I hate it.”

It turns out that while people were perfectly fine with a dark mode that inverts the colours of text, it felt really weird and icky to do the same with sheet music.

On the one hand, this seems odd. After all, sheet music is a writing system like any other. If you’re fine with light text on a dark background, why doesn’t that hold for light sheet music on a dark background?

But on the other hand, sheet music is also like an image. And we don’t invert the colours of our images when we add a dark mode to our CSS.

With that in mind, I went back to the drawing board and this time treated the sheet music SVGs as being intrinsicly dark-on-light, rather than a stylistic choice. It meant a few more CSS rules, but I’m happy with the final result. You can see it in action by visiting a tune page and toggling your device’s “appearance” settings between light and dark.

If you’re a member of The Session, I also added a toggle switch to your member profile so you can choose dark or light mode regardless of your device settings.

Cascading Style Sheets

There are three ways—that I know of—to associate styles with markup.

External CSS

This is probably the most common. Using a link element with a rel value of “stylesheet”, you point to a URL using the href attribute. That URL is a style sheet that is applied to the current document (“the relationship of the linked resource it is that is a ‘stylesheet’ for the current document”).

<link rel="stylesheet" href="/path/to/styles.css">

In theory you could associate a style sheet with a document using an HTTP header, but I don’t think many browsers support this in practice.

You can also pull in external style sheets using the @import declaration in CSS itself, as long as the @import rule is declared at the start, before any other styles.

@import url('/path/to/more-styles.css');

When you use link rel="stylesheet" to apply styles, it’s a blocking request: the browser will fetch the style sheet before rendering the HTML. It needs to know how the HTML elements will be painted to the screen so there’s no point rendering the HTML until the CSS is parsed.

Embedded CSS

You can also place CSS rules inside a style element directly in the document. This is usually in the head of the document.

<style>
element {
    property: value;
}
</style>

When you embed CSS in the head of a document like this, there is no network request like there would be with external style sheets so there’s no render-blocking behaviour.

You can put any CSS inside the style element, which means that you could use embedded CSS to load external CSS using an @import statement (as long as that @import statement appears right at the start).

<style>
@import url('/path/to/more-styles.css');
element {
    property: value;
}
</style>

But then you’re back to having a network request.

Inline CSS

Using the style attribute you can apply CSS rules directly to an element. This is a universal attribute. It can be used on any HTML element. That doesn’t necessarily mean that the styles will work, but your markup is never invalidated by the presence of the style attribute.

<element style="property: value">
</element>

Whereas external CSS and embedded CSS don’t have any effect on specificity, inline styles are positively radioactive with specificity. Any styles applied this way are almost certain to over-ride any external or embedded styles.

You can also apply styles using JavaScript and the Document Object Model.

element.style.property = 'value';

Using the DOM style object this way is equivalent to inline styles. The radioactive specificity applies here too.

Style declarations specified in external style sheets or embedded CSS follow the rules of the cascade. Values can be over-ridden depending on the order they appear in. Combined with the separate-but-related rules for specificity, this can be very powerful. But if you don’t understand how the cascade and specificity work then the results can be unexpected, leading to frustration. In that situation, inline styles look very appealing—there’s no cascade and everything has equal specificity. But using inline styles means foregoing a lot of power—you’d be ditching the C in CSS.

A common technique for web performance is to favour embedded CSS over external CSS in order to avoid the extra network request (at least for the first visit—there are clever techniques for caching an external style sheet once the HTML has already loaded). This is commonly referred to as inlining your CSS. But really it should be called embedding your CSS.

This language mix-up is not a hill I’m going to die on (that hill would be referring to blog posts as blogs) but I thought it was worth pointing out.

Influence

Hidde gave a great talk recently called On the origin of cascades (by means of natural selectors):

It’s been 25 years since the first people proposed a language to style the web. Since the late nineties, CSS lived through years of platform evolution.

It’s a lovely history lesson that reminded me of that great post by Zach Bloom a while back called The Languages Which Almost Became CSS.

The TL;DR timeline of CSS goes something like this:

Håkon and Bert joined forces and that’s what led to the Cascading Style Sheet language we use today.

Hidde looks at how the concept of the cascade evolved from those early days. But there’s another idea in Håkon’s proposal that fascinates me:

While the author (or publisher) often wants to give the documents a distinct look and feel, the user will set preferences to make all documents appear more similar. Designing a style sheet notation that fill both groups’ needs is a challenge.

The proposed solution is referred to as “influence”.

The user supplies the initial sheet which may request total control of the presentation, but — more likely — hands most of the influence over to the style sheets referenced in the incoming document.

So an author could try demanding that their lovely styles are to be implemented without question by specifying an influence of 100%. The proposed syntax looked like this:

h1.font.size = 24pt 100%

More reasonably, the author could specify, say, 40% influence:

h2.font.size = 20pt 40%

Here, the requested influence is reduced to 40%. If a style sheet later in the cascade also requests influence over h2.font.size, up to 60% can be granted. When the document is rendered, a weighted average of the two requests is calculated, and the final font size is determined.

Okay, that sounds pretty convoluted but then again, so is specificity.

This idea of influence in CSS reminds me of Cap’s post about The Sliding Scale of Giving a Fuck:

Hold on a second. I’m like a two-out-of-ten on this. How strongly do you feel?

I’m probably a six-out-of-ten, I replied after a couple moments of consideration.

Cool, then let’s do it your way.

In the end, the concept of influence in CSS died out, but user style sheets survived …for a while. Now they too are as dead as a dodo. Most people today aren’t aware that browsers used to provide a mechanism for applying your own visual preferences for browsing the web (kind of like Neopets or MySpace but for literally every single web page …just think of how empowering that was!).

Even if you don’t mourn the death of user style sheets—you can dismiss them as a power-user feature—I think it’s such a shame that the concept of shared influence has fallen by the wayside. Web design today is dictatorial. Designers and developers issue their ultimata in the form of CSS, even though technically every line of CSS you write is a suggestion to a web browser—not a demand.

I wish that web design were more of a two-way street, more of a conversation between designer and end user.

There are occassional glimpses of this mindset. Like I said when I added a dark mode to my website:

Y’know, when I first heard about Apple adding dark mode to their OS—and also to CSS—I thought, “Oh, great, Apple are making shit up again!” But then I realised that, like user style sheets, this is one more reminder to designers and developers that they don’t get the last word—users do.

Dark mode revisited

I added a dark mode to my website a while back. It was a fun thing to do during Indie Web Camp Amsterdam last year.

I tied the colour scheme to the operating system level. If you choose a dark mode in your OS, my website will adjust automatically thanks to the prefers-color-scheme: dark media query.

But I’ve seen notes from a few friends, not about my site specifically, but about how they like having an explicit toggle for dark mode (as well as the media query). Whenever I read those remarks, I’d think “I’m really not sure I’ve got time to deal with adding that kind of toggle to my site.”

But then I realised, “Jeremy, you absolute muffin! You’ve had a theme switcher on your website for almost two decades now!”

Doh! I had forgotten about that theme switcher. It dates back to the early days of CSS. I wanted my site to be a demonstration of how you could apply different styles to the same underlying markup (this was before the CSS Zen Garden came along). Those themes are very dated now, but if you like you can view my site with a Zeldman theme or a sci-fi theme.

To offer a dark-mode theme for my site, all I had to do was take the default stylesheet, pull out the custom properties from the prefers-color-scheme: dark media query, and done. It took less than five minutes.

So if you want to view my site in dark mode, it’s one of the options in the “Customise” dropdown on every page of the website.

Dark mode

I had a very productive time at Indie Web Camp Amsterdam. The format really lends itself to getting the most of a weekend—one day of discussions followed by one day of hands-on making and doing. You should definitely come along to Indie Web Camp Brighton on October 19th and 20th to experience it for yourself.

By the end of the “doing” day, I had something fun to demo—a dark mode for my website.

Y’know, when I first heard about Apple adding dark mode to their OS—and also to CSS—I thought, “Oh, great, Apple are making shit up again!” But then I realised that, like user style sheets, this is one more reminder to designers and developers that they don’t get the last word—users do.

Applying the dark mode styles is pretty straightforward in theory. You put the styles inside this media query:

@media (prefers-color-scheme: dark) {
...
}

Rather than over-riding every instance of a colour in my style sheet, I decided I’d do a little bit of refactoring first and switch to using CSS custom properties (or variables, if you will).

:root {
  --background-color: #fff;
  --text-color: #333;
  --link-color: #b52;
}
body {
  background-color: var(--background-color);
  color: var(--text-color);
}
a {
  color: var(--link-color);
}

Then I can over-ride the custom properties without having to touch the already-declared styles:

@media (prefers-color-scheme: dark) {
  :root {
    --background-color: #111416
    --text-color: #ccc;
    --link-color: #f96;
  }
}

All in all, I have about a dozen custom properties for colours—variations for text, backgrounds, and interface elements like links and buttons.

By using custom properties and the prefers-color-scheme media query, I was 90% of the way there. But the devil is in the details.

I have SVGs of sparklines on my homepage. The SVG has a hard-coded colour value in the stroke attribute of the path element that draws the sparkline. Fortunately, this can be over-ridden in the style sheet:

svg.activity-sparkline path {
  stroke: var(--text-color);
}

The real challenge came with the images I use in the headers of my pages. They’re JPEGs with white corners on one side and white gradients on the other.

header images

I could make them PNGs to get transparency, but the file size would shoot up—they’re photographic images (with a little bit of scan-line treatment) so JPEGs (or WEBPs) are the better format. Then I realised I could use CSS to recreate the two effects:

  1. For the cut-out triangle in the top corner, there’s clip-path.
  2. For the gradient, there’s …gradients!
background-image: linear-gradient(
  to right,
  transparent 50%,
  var(—background-color) 100%
);

Oh, and I noticed that when I applied the clip-path for the corners, it had no effect in Safari. It turns out that after half a decade of support, it still only exists with -webkit prefix. That’s just ridiculous. At this point we should be burning vendor prefixes with fire. I can’t believe that Apple still ships standardised CSS properties that only work with a prefix.

In order to apply the CSS clip-path and gradient, I needed to save out the images again, this time without the effects baked in. I found the original Photoshop file I used to export the images. But I don’t have a copy of Photoshop any more. I haven’t had a copy of Photoshop since Adobe switched to their Mafia model of pricing. A quick bit of searching turned up Photopea, which is pretty much an entire recreation of Photoshop in the browser. I was able to open my old PSD file and re-export my images.

LEGO clone trooper Brighton bandstand Scaffolding Tokyo Florence

Let’s just take a moment here to pause and reflect on the fact that we can now use CSS to create all sorts of effects that previously required a graphic design tool like Photoshop. I could probably do those raster scan lines with CSS if I were smart enough.

dark mode

This is what I demo’d at the end of Indie Web Camp Amsterdam, and I was pleased with the results. But fate had an extra bit of good timing in store for me.

The very next day at the View Source conference, Melanie Richards gave a fantastic talk called The Tailored Web: Effectively Honoring Visual Preferences (seriously, conference organisers, you want this talk on your line-up). It was packed with great insights and advice on impementing dark mode, like this little gem for adjusting images:

@media (prefers-color-scheme: dark) {
  img {
    filter: brightness(.8) contrast(1.2);
  }
}

Melanie also pointed out that you can indicate the presence of dark mode styles to browsers, although the mechanism is yet to shake out. You can do it in CSS:

:root {
  color-scheme: light dark;
}

But you can also do it in HTML:

That allows browsers to swap out replaced content; interface elements like form fields and dropdowns.

Oh, and one other addition I added after the fact was swapping out map imagery by using the picture element to point to darker map tiles:

<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.mapbox.com/styles/v1/mapbox/dark-v10/static...">
<img src="https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/static..." alt="map">
</picture>

light map dark map

So now I’ve got a dark mode for my website. Admittedly, it’s for just one of the eight style sheets. I’ve decided that, while I’ll update my default styles at every opportunity, I’m going to preservethe other skins as they are, like the historical museum pieces they are.

If you’re on the latest version of iOS, go ahead and toggle the light and dark options in your system preferences to flip between this site’s colour schemes.

Code print

You know what I like? Print stylesheets!

I mean, I’m not a huge fan of trying to get the damn things to work consistently—thanks, browsers—but I love the fact that they exist (athough I’ve come across a worrying number of web developers who weren’t aware of their existence). Print stylesheets are one more example of the assumption-puncturing nature of the web: don’t assume that everyone will be reading your content on a screen. News articles, blog posts, recipes, lyrics …there are many situations where a well-considered print stylesheet can make all the difference to the overall experience.

You know what I don’t like? QR codes!

It’s not because they’re ugly, or because they’ve been over-used by the advertising industry in completely inapropriate ways. No, I don’t like QR codes because they aren’t an open standard. Still, I must grudgingly admit that they’re a convenient way of providing a shortcut to a URL (albeit a completely opaque one—you never know if it’s actually going to take you to the URL it promises or to a Rick Astley video). And now that the parsing of QR codes is built into iOS without the need for any additional application, the barrier to usage is lower than ever.

So much as I might grit my teeth, QR codes and print stylesheets make for good bedfellows.

I picked up a handy tip from a Smashing Magazine article about print stylesheets a few years back. You can the combination of a @media print and generated content to provide a QR code for the URL of the page being printed out. Google’s Chart API provides a really handy shortcut for generating QR codes:

https://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=http://example.com

Except that there’s no telling how long that will continue to work. Google being Google, they’ve deprecated the simple image chart API in favour of the over-engineered JavaScript alternative. So just as I recently had to migrate all my maps over to Leaflet when Google changed their Maps API from under the feet of developers, the clock is ticking on when I’ll have to find an alternative to the Image Charts API.

For now, I’ve got the QR code generation happening on The Session for individual discussions, events, recordings, sessions, and tunes. For the tunes, there’s also a separate URL for each setting of a tune, specifically for printing out. I’ve added a QR code there too.

Experimenting with print stylesheets and QR codes.

I’ve been thinking about another potential use for QR codes. I’m preparing a new talk for An Event Apart Seattle. The talk is going to be quite practical—for a change—and I’m going to be encouraging people to visit some URLs. It might be fun to include the biggest possible QR code on a slide.

I’d better generate the images before Google shuts down that API.

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.

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.

Print styles

I really wanted to make sure that the print styles for Resilient Web Design were pretty good—or at least as good as they could be given the everlasting lack of support for many print properties in browsers.

Here’s the first thing I added:

@media print {
  @page {
    margin: 1in 0.5in 0.5in;
    orphans: 4;
    widows: 3;
  }
}

That sets the margins of printed pages in inches (I could’ve used centimetres but the numbers were nice and round in inches). The orphans: 4 declaration says that if there’s less than 4 lines on a page, shunt the text onto the next page. And widows: 3 declares that there shouldn’t be less than 3 lines left alone on a page (instead more lines will be carried over from the previous page).

I always get widows and orphans confused so I remind myself that orphans are left alone at the start; widows are left alone at the end.

I try to make sure that some elements don’t get their content split up over page breaks:

@media print {
  p, li, pre, figure, blockquote {
    page-break-inside: avoid;
  }
}

I don’t want headings appearing at the end of a page with no content after them:

@media print {
  h1,h2,h3,h4,h5 {
    page-break-after: avoid;
  }
}

But sections should always start with a fresh page:

@media print {
  section {
    page-break-before: always;
  }
}

There are a few other little tweaks to hide some content from printing, but that’s pretty much it. Using print preview in browsers showed some pretty decent formatting. In fact, I used the “Save as PDF” option to create the PDF versions of the book. The portrait version comes from Chrome’s preview. The landscape version comes from Firefox, which offers more options under “Layout”.

For some more print style suggestions, have a look at the article I totally forgot about print style sheets. There’s also tips and tricks for print style sheets on Smashing Magazine. That includes a clever little trick for generating QR codes that only appear when a document is printed. I’ve used that technique for some page types over on The Session.

Whatever works for you

I was one of the panelists on the most recent episode of the Shop Talk Show along with Nicole, Colin Megill, and Jed Schmidt. The topic was inline styles. Well, not quite. That’s not a great term to describe the concept. The idea is that you apply styling directly to DOM nodes using JavaScript, instead of using CSS selectors to match up styles to DOM nodes.

It’s an interesting idea that I could certainly imagine being useful in certain situations such as dynamically updating an interface in real time (it feels a bit more “close to the metal” to reflect the state updates directly rather than doing it via class swapping). But there are many, many other situations where the cascade is very useful indeed.

I expressed concern that styling via JavaScript raises the barrier to styling from a declarative language like CSS to a programming language (although, as they pointed out, it’s more like moving from CSS to JSON). I asked whether it might not be possible to add just one more layer of abstraction so that people could continue to write in CSS—which they’re familiar with—and then do JavaScript magic to match those selectors, extract those styles, and apply them directly to the DOM nodes. Since recording the podcast, I came across Glen Maddern’s proposal to do exactly that. It makes sense to me try to solve the perceived problems with CSS—issues of scope and specificity—without asking everyone to change the way they write.

In short, my response was “hey, like, whatever, it’s cool, each to their own.” There are many, many different kinds of websites and many, many different ways to make them. I like that.

So I was kind of surprised by the bullishness of those who seem to honestly believe that this is the way to build on the web, and that CSS will become a relic. At one point I even asked directly, “Do you really believe that CSS is over? That all styles will be managed through JavaScript from here on?” and received an emphatic “Yes!” in response.

I find that a little disheartening. Chris has written about the confidence of youth:

Discussions are always worth having. Weighing options is always interesting. Demonstrating what has worked (and what hasn’t) for you is always useful. There are ways to communicate that don’t resort to dogmatism.

There are big differences between saying:

  • You can do this,
  • You should do this, and
  • You must do this.

My take on the inline styles discussion was that it fits firmly in the “you can do this” slot. It could be a very handy tool to have in your toolbox for certain situations. But ideally your toolbox should have many other tools. When all you have is a hammer, yadda, yadda, yadda, nail.

I don’t think you do your cause any favours by jumping straight to the “you must do this” stage. I think that people are more amenable to hearing “hey, here’s something that worked for me; maybe it will work for you” rather than “everything you know is wrong and this is the future.” I certainly don’t think that it’s helpful to compare CSS to Neanderthals co-existing with JavaScript Homo Sapiens.

Like I said on the podcast, it’s a big web out there. The idea that there is “one true way” that would work on all possible projects seems unlikely—and undesirable.

“A ha!”, you may be thinking, “But you yourself talk about progressive enhancement as if it’s the one try way to build on the web—hoisted by your own petard.” Actually, I don’t. There are certainly situations where progressive enhancement isn’t workable—although I believe those cases are rarer than you might think. But my over-riding attitude towards any questions of web design and development is:

It depends.

Print stylesheets

CSS Naked Day was fun. It felt almost voyeuristic to peek under the CSS skirts of so many sites. It also made me realise that the browser default styles are what people are going to see if they decide to print out a page from many CSS-based sites.

I’ve had a rudimentary print stylesheet in place for Adactio for a while now, although I should probably revisit it and tweak it some time. But a lot of other sites that I’ve designed have been woefully lacking in print stylesheets.

For instance, the situation with the DOM Scripting site was brought home to me when I received this message from Adam Messinger:

Would it be possible to get a print stylesheet for the errata page that does a better job of preserving the table layout? As it is now, it’s sometimes hard to tell which page numbers match up to what errors. Just some borders on the table would help a lot.

That one made me slap my forehead. Of course! If ever there was a web page that was likely to be printed out, the errata for a printed book would be it.

As well as adding borders to the errata table, I set to work on creating a stylesheet for the whole site. It was fairly quickly and painless. I hid the navigation, let the content flow into one column, set the font sizes in points and used a minimum amount of colour.

DOM Scripting blog on screen DOM Scripting blog in print

I did much the same for Jessica’s site, WordRidden.

WordRidden on screen WordRidden in print

Principia Gastronomica was crying out for a print stylesheet. Half of the entries on that blog are recipes. Most people don’t have computer screens in their kitchens so it’s very likely that the recipes will be printed out.

A lot of the entries on Principia Gastronomica make heavy use of images. Everyone likes pictures of food, after all. I was faced with the question of whether or not to include these images in the printed versions.

In the end, I decided not to include the images. Firstly, it’s a real pain trying to ensure that the images don’t get split over two pages (page-break-before would be a draconian and wasteful solution). Secondly, I bowed to Jessica’s wisdom and experience in this matter. She often prints out recipes from sites like Epicurious and, when she does, she wants just the facts. Also, these are pages that are likely to printed out in the home, probably on a basic inkjet printer, rather than in an office equipped with a nice laser printer.

Principia Gastronomica on screen Principia Gastronomica in print

If you’re implementing a print stylesheet for your site, I highly recommend reading Richard’s guide, The Elements of Typographic Style Applied to the Web. All the advice is good for screen styles, but is especially applicable to print.

These articles on A List Apart are also required reading:

In an interview over on Vitamin, Eric makes the point that context is everything when deciding which stylesheets to serve up. Clearly, articles on a A List Apart are likely to printed out to be read, but the front page is more likely to be printed out to get a hard copy of the design.

For a detailed anatomy of a print stylesheet, be sure to read the latest in Mark’s Five Simple Steps to Typesetting on the web series: Printing the web.

Naked

My site has no stylesheets (“how does it smell?”, etc.) but you probably won’t even notice because chances are your reading this in a feedreader.

In any case, it’s nice just to look at the flow of the document sans styles. Notice the “More information” h2 tag that is normally hidden from view. With styles enabled, the visual layout makes this heading redundant but without styles, or for non-visual user-agents, it’s a useful marker.

The man responsible for this CSS nakedness is Dustin Diaz, himself no stranger to nudity.

I had a pleasant chat with Dustin yesterday which forms the basis for the latest episode of his podcast. It was fun for me. I don’t know how much fun it’ll be to listen back to. I ramble on about JavaScript, comments, food blogging and George Clooney. Listen for yourself.