A nice modern resource listing the now huge range of CSS properties on one page. There’s a neat search with autosuggest and each listed property links to a page with a short description plus MDN browser support data.
I’ve written before that CSS transition is great for simple animations triggered by an event. You might want to transition something in response to a focus or hover event. Or, perhaps your use case is that the user activates a button to launch a previously-hidden dialog element and you want to use transition to animate the dialogue’s entrance and exit.
I’m partial to going down the rabbit-hole on a niche aspect of front-end development. For example a few years ago I got the urge to dig into what’s going on with containers and items in Flexbox-powered layouts and noted my findings in Flexbox-fu. I do it to go beyond the thing’s theory and into its practical application for solving real web development challenges; to gain a deeper understanding of why things behave the way they do. These deep dives take time but are rewarding; usually I’ll learn about more than I expected.
Recently I dug into the characteristics and behaviour of the CSS outline property. The catalyst was seeing Heydon Pickering’s clever use of outline to automate divider lines within a flexbox powered navigation menu. I couldn’t fathom how it works so decided to reverse-engineer it. More on Heydon’s trick later, but I’ll start with a recap of what outline is good for.
I purchased Scott’s course back in 2021 and immediately liked it, but hadn’t found the space to complete it until now. Anyway, I’m glad I have as it’s well structured and full of insights and practical tips. I’ll use this post to summarise my main takeaways.
Having completed the course I have much more rounded knowledge in the following areas:
Why performance matters to users and business
Performance-related metrics and “moments”: defining fast and slow
Identifying performance problems: the tools and how to use them
Making things faster, via various good practices and fixes
I’ll update this post soon to add some key bullet-points for each of the above headings.
This is a wonderful guide that’s choc-full of practical examples.
CSS container queries help us to write a truly fluid components that change based on their container size. In the next few years, we’ll see less media queries and more container queries.
Lots of inspiration here for when I start using Container Queries in earnest.
Scott proposes an interview question relating to web standards and intelligent use of JavaScript.
How would you attempt to build Wordle (...or some other complex app) if you could only use HTML and CSS? Which features of that app would make more sense to build with JavaScript than with other technologies? And, can you imagine a change or addition to the HTML or CSS standard that could make any of those features more straight-forward to build?
Discussing any approaches to this challenge will reveal the candidate's broad knowledge of web standards–including new and emerging HTML and CSS features–and as a huge benefit, it would help select for the type of folks who are best suited to lead us out of the JavaScript over-reliance problems that are holding back the web today.
I hate interviews (and the mere thought of interviews), but I could handle being asked a question like this.
David cleverly uses CSS alone (and only a few lines) to show a “back to top” link only after the user has started scrolling, then pin its position to the bottom-left of the screen.
The clever margin-top: 110vh combined with position: sticky – since 110vh is slightly more than 100% of the page’s height – gives the link a starting position that is not initially visible but becomes visible once the user starts scrolling. The bottom: 0 then ensures that when the user continues scrolling vertically the link “sticks” to the bottom-left of the page.
So little code and so clever!
PS if you’re wondering why you’d want a “back to top” link in the first place, it’s to let a user who has scrolled far down a long page to easily get back to options located at the top. See NN Group’s Back-to-Top Button Design Guidelines.
There’s a great section on Source order and layers in Every Layout’s Imposter layout. It’s a reminder that when needing to layer one element on top of the other you should:
favour a modern layout approach such as CSS Grid over absolute positioning; and
not apply z-index unless it’s necessary.
which elements appear over which is, by default, a question of source order. That is: if two elements share the same space, the one that appears above the other will be the one that comes last in the source.
z-index is only necessary where you want to layer positioned elements irrespective of their source order. It’s another kind of override, and should be avoided wherever possible.
An arms race of escalating z-index values is often cited as one of those irritating but necessary things you have to deal with using CSS. I rarely have z-index problems, because I rarely use positioning, and I’m mindful of source order when I do.
Matthias feels that the recent slew of additions to CSS have completely changed the game.
this time, something feels different… the changes coming to CSS are so fundamental on so many levels that it almost feels like a singularity. There is now the CSS before and the CSS after the early 2020s.
Want to emulate and confidently design a layout that leverages the potential of CSS Grid in any of the major design tools like Figma, Adobe XD, or Sketch? Not possible. Want to define a color in one of the wide gamut color spaces like OKLCH, which result in more vibrant and natural colors on modern screens, maybe by using a color picker? Not possible. You want to simulate fluid typography that dynamically scales font sizes based on the viewport or container size and also define minimum and maximum values like you can do it in CSS with clamp()? Not possible. Or how about defining a fallback font in case your web font doesn’t load? Good luck using any screen design tool on the market. Not only are all of those things – very clearly – important design decisions, but they are also easily possible with just a few lines of CSS. In this new era of CSS, the design tools are now the limiting factor.
He also hopes and suggests that CSS might become more respected and teams might “shift left” with regard to prototyping in the browser.
What I expect to see overall is that the perception and thus the role of CSS in the design process will change from being mainly a presentational styling tool at the end of the waterfall to a tool that is being used at the heart of making design decisions early on. The value of a designer who knows how to prototype and build web components with modern CSS will therefore increase a lot. As a design engineering freelancer, I’m noticing this already.
Applying opacity to an existing colour value is a pretty common design requirement, and here Chris presents five ways to achieve it.
I’ll admit that the explosion of colour models is one aspect of CSS that leaves me dizzy, so this explanation framed around a practical requirement really helps. The main approaches presented by Chris are:
In responsive design we generally want a single component to get different styles in different contexts. Up until recently the prevailing method of context-awareness was to use a CSS media query to query the viewport size. This wasn’t ideal. For example you might want an component to be styled differently when in a narrow context such as a sidebar (regardless of the device size), and viewport-based queries don’t help with that.
My pen is pretty trivial, but the goal was specifically to do the most minimal test that lets me test-drive the key syntax. It turns out that it’s quite straightforward.
Define an element as a container:
.sidebar{container: ctr-sidebar / inline-size;}
Change the styles of another element (.foo) when it’s inside that container and the container’s inline-size (the logical property name for width) matches a given query:
@container ctr-sidebar (max-width: 300px){.foo{
// context-specific styles go here
}}
Note that you could also omit the ctr-sidebar context in the above query, if you wanted the change to apply in all defined containers.
I’m wary of list-based clickbait – and Adam’s recent 6 CSS snippets every front-end developer should know in 2023 feels like that – however I like this modern and minimal approach to creating a circle. I’ve previously seen aspect-ratio: 1 used to create a square box and it’s a lovely shorthand for “make width and height equal”. It makes sense that you can use it for a circle too, just by adding some border-radius.
Responsive design for tables is tricky. Sure, you can just make the table’s container horizontally scrollable but that’s more a developer convenience than a great user experience. And if you instead try to do something more clever, you can run into challenges as I did in the past. Still, we should strive to design good narrow screen user experiences for tables, alongside feasible technical solutions to achieve them.
In terms of UI design, I was interested to read Erik Kennedy’s recent newsletter on The best way to display tables on mobile. Erik lists three different approaches, which are (in reverse order of his preference):
Hide the least important columns
Cards with rows of Label-Value pairs
More radical “remix” as a “Mobile List”
Another article worth checking is Andrew Coyle’s The Responsive Table. He describes the following approaches:
Horizontal overflow table (inc. fixed first column)
The syntax is pretty close to what we’re used to doing with Sass, which is great!
Also, I’m now also clear that nested selectors must always start with a symbol rather than a letter. Often they would naturally do so anyway, for example when nesting a class since that already starts with a symbol (a full stop). But in cases where they wouldn’t – essentially only when nesting an “element selector” – we start it with an “&”. So:
main {
& article { ... }
}
Straightforward enough!
Regarding browser support for CSS nesting, at the time of writing it is available in Chrome and Safari Technology Preview only.
I would therefore only use it for demos and for the most non-essential enhancements. We’ll need to hold off any full-scale switch from Sass nesting to CSS nesting for large and important production websites until this is in Firefox and standard Safari, and until a sufficient percentage of users has the up-to-date versions. So a little while away yet, but given the current rate of browser updates, likely sooner than we might think!
This article is not about when or why you would use visually-hidden content. There’s a number of excellent articles that discuss these questions in detail, notably Scott O’Hara’s Inclusively Hidden. But most of them don’t go into much detail about the specific CSS involved — why do we use this particular pattern, with these specific properties? So today I’m going to dissect it, looking at each of the properties in turn, why it’s there, and why it isn’t something else.
Something I’ve found interesting while reviewing recent code test submissions (within job applications) at work is that more developers than I’d expect still use display: inline-block when they need to lay out multiple elements horizontally such as the items in a navigation menu. It’s interesting because Flexbox – which has now been around for almost 10 years – gives you a modern, purpose-built solution to that.
Of course, there is no crime in taking the inline-block approach. It’s an option. And I did take a moment just to challenge my assumptions. But having given it a little thought, I am pretty convinced that Flexbox is the better approach and so I think their choice is worth a query.
Here’s why I think Flexbox is much better:
Modern CSS layout is purpose-built for constructing multi-element layouts. Older methods were lacking, quirky and slightly hacky. Using (and knowing to use) purpose-built tools is generally a good thing for reliability, predictability and scalability.
Modern CSS layout provides more control, because it’s fundamentally different. You get a parent context (the flex container or grid) that lets you style the context (with gap, for example). We didn’t have this before.
Flexbox is built for responsiveness, i.e. built for the modern era. inline-block was not.
the default align-items:stretch means that items laid out in a row are automatically full parent-height which is often desirable for larger touch targets and achieving hover styles.
inline-block retains some of the properties of inline that are undesirable for this type of use-case. Who can be bothered with whitespace in the code appearing on the screen, or having to work with vertical-align when you don’t need to.
I also don’t see any reason to not use Flexbox. It’s conventional (see for example navigation menus on BBC, Tetralogical), recommended by CSS experts (Rachel Andrew, Jen Simmons etc), performant and well-supported by browsers. You are not going “fancy”, “cutting edge” or “overkill” by using Flexbox. For the “horizontal menu” use case, it’s simply a more suitable choice than the older alternatives.
Related: Chris Coyier’s article When do you use inline block is an excellent investigation into whether any necessary uses for inline-block remain. I reserve the right to change my mind on this, but aside from the “apply transform to an inline element” use case I can’t really see any that have not now been superseded.
By day I’m currently working on our Design System’s Table component. In order to achieve a design spec where the table has no bottom-border I needed to set:
all cells in the final row of the <tfoot> to have no bottom-border; but also
if there is no <tfoot> then set all cells in the final row of the <tbody> to have no bottom-border.
Modern CSS’s support for writing selectors which traverse the DOM up, down and sideways is pretty amazing here.
(Some BEM stuff renamed for brevity but that’s the gist of it)
In the past we’ve had to bloat the backend layer with complex and awkward logic that adds “convenience classes” like .fe-Table-bodyLastRow but as Eric Meyer has been saying:has() in particular is going to remove the need for those convenience classes.
Great tip here from Jhey. He advises using a button with ARIA and a little JavaScript for your dark-mode toggle. And to apply the dark styles, use a CSS selector which targets the :root parent of the button when in “pressed” state and sets a root-level custom property to “on”.
:root:has([aria-pressed=true]){--dark:1;}
Seriously clever stuff!
And aside from the CSS, I really like the way Jhey advocates using a button rather than a form element such as a checkbox for this kind of interface, much like Léonie did recently.
Back in June I attended CSS Day in Amsterdam. One of my favourite talks was The CSS Cascade – A Deep Dive by Bramus van Damme. Bramus covered everything we wanted to know about the cascade but were afraid to ask! And that included an introduction to CSS Cascade Layers – the latest game-changing CSS feature.
For example, currently if we have the selectors ul[class] defined early in the “reset” section of our styles and .nav defined later in a “components” section, the former selector wins due to its higher specificity. That’s not what we want – we want our component styles to override our global styles. This has previously led people to hack around the problem by adding extra specificity to the latter selector, or by wrapping :where() around the former to decrease its specificity, neither of which are desirable. With layers we can do:
@layer reset, components;@layer reset{ul[class]{/* set margin to 0 here */}}@layer components{.nav{/* give .nav ul custom margins */}}
And .nav gets that higher specificity that we want.
I also like that layers align well with an ITCSS approach.
Taking layers for a spin
Cascade Layers are relatively newly-supported in browsers but pretty all-or-nothing in CSS terms to the extent that using them in a progressively-enhanced approach isn’t really an option. So I wouldn’t yet advocate using Layers on an important production website. However there’s nothing to stop me test-driving them on my personal site. Users on old browsers still get the essential content (although very few styles) and for this site, that’s good enough. So I’ve taken the plunge.
And it’s working really well already! Recently while rewriting some CSS I found that if the top of my styles featured a reset which disabled margins on h2 but I also wanted an h2 to take on margins when used within a low-specificity flow utility, the reset style was winning and that was frustrating. But when I moved my reset styles into a reset layer and my layout styles into a layouts layer with the layer order set as reset, layouts then the layout styles win! Really cool.
At work we’ve recently been shown a couple of design proposals where truncation was presented as a solution to the perceived problem of long and unwieldy content, for example a long description in a table cell. However following good discussions, as a wider team we’re now leaning towards avoiding truncation as an approach. Truncation can present accessibility issues and as Karen McGrane says truncation is not a good content strategy. I reckon we should just let long content wrap, and design for that to look OK.
And when natural wrapping doesn’t cut it – like when you’re tackling very long words in confined spaces – reach for overflow-wrap: break-word as suggested in Ahmad Shadeed’s excellent Handling Short And Long Content In CSS.
The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters match at least one element. But, it's more than a "parent" selector. That's a nice way to market it. The not so appealing way might be the "conditional environment" selector. But that doesn't have quite the same ring to it. How about the “family” selector?
The CSS :has() pseudo-class is a game-changer and can do more than act as a parent selector, as Jhey illustrates.
Our Design System team has recently received “new component requests” for some custom filtering controls. These look like custom-styled <select>s however their “options” appear more like checkboxes and radio buttons. I think the inspiration was Carbon Design System’s Dropdown component and the idea is to bring consistency to filtering controls in forms. Although it’s not yet time to fully explore this and make a yay/nay decision on the request, I’ve been doing some initial thinking.
(Note: this post is kinda a journey and work-in-progress. I’ll return to complete it and tidy up. For now it serves as a handy log of my research.)
When this was first mooted without guide designs, I assumed we’d be making a custom select. Filament Group have previously shown how to style one of those, although that only affects the “trigger” part. CSS can’t yet style the options. That then led me to check in on the progress of Open UI’s selectmenu element which does support styling the options however it appears that it’s far from road-ready.
However then I saw the designs and realised that while the outside looks like a select, the options look like a group of checkboxes or (kinda) like radio buttons, rather than typical <select> options. And of course the checkboxes and radio buttons themselves are custom-styled.
I’ve started trialling different HTML and technologies for the “simple” responsive images (i.e. not art-directed per breakpoint) used in blog articles on this site. I’m continuing to lean on Cloudinary as my free image host, CDN and format-conversion service. But at the HTML level I’ve moved from a complicated <img srcset> based approach that includes many resized versions of the same image. I now use a simpler <picture> and <source> based pattern that keeps the number of images and breakpoints low and instead – by using the source element’s type attribute – takes advantage of the performance gains offered by the new avif and webp image formats.
My new approach is based on advice in Jake Archibald’s brilliant article Halve the size of images by optimising for high density displays. Jake explains that the majority of your traffic likely consists of users with high density screens so when we can combine optimising for that and making performance gains in a progressively enhanced way, we should!
Jake offers a “lazy but generally good enough” approach:
Here's the technique I use for most images on this blog: I take the maximum size the image can be displayed in CSS pixels, and I multiply that by two, and I encode it at a lower quality, as it'll always be displayed at a 2x density or greater. Yep. That's it. For 'large' images in blog posts like this, they're at their biggest when the viewport is 799px wide, where they take up the full viewport width. So I encode the image 1,598 pixels wide.
<picture><sourcetype="image/avif"srcset="red-panda.avif"/><sourcetype="image/webp"srcset="red-panda.webp"/><imgsrc="red-panda.jpg"width="1598"height="1026"alt="A red panda"/></picture>
So, if you want your images to be as sharp as possible, you need to target images at the user's device pixels, rather than their CSS pixels. To encode a 2x image, I throw it into Squoosh.app, and zoom it out until it's the size it'll be displayed on a page. Then I just drag the quality slider as low as it'll go before it starts looking bad.
Taking Jake’s guidance and tweaking it for my Cloudinary-based context, my recent post April 2022 mixtape included its image like so:
<figure><picture><sourcetype="image/avif"srcset="https://res.cloudinary.com/…/f_avif,q_auto,w_1292/v1654433393/mato_1500_squooshed_mozjpg_xjrkhl.jpg"/><sourcetype="image/webp"srcset="https://res.cloudinary.com/…/f_webp,q_auto,w_1292/v1654433393/mato_1500_squooshed_mozjpg_xjrkhl.jpg"/><imgclass="u-full-parent-width"src="https://res.cloudinary.com/…/f_jpg,q_auto,w_1292/v1654433393/mato_1500_squooshed_mozjpg_xjrkhl.jpg"width="1292"height="1292"alt="Side A of the 7-inch vinyl release of Mato’s “Summer Madness"loading="lazy"decoding="async"/></picture><figcaption>Mato’s “Summer Madness”, as featured on the mix</figcaption></figure>
And my process was as follows:
Take a photo (for me, that’ll be on my phone). Without doing anything special it’ll already be wide enough.
Apple use the HEIC format. To get around that, do: Share, Copy, open Files > HEIC to JPG, paste and it’ll save as JPG.
resize it to 1300 wide (in my current layout 1292 is twice as wide (2 × 646) as the image would need to go, and I just round up to 1300)
reduce its quality a bit (stopping before it gets noticeably bad)
Encode that as a mozjpg which gave the best size reduction and as far as I can tell, is a safe approach to use.
Upload to my Cloudinary account then copy its new Cloudinary URL.
Prepare the image HTML per the above snippet. The first sourcetells Cloudinary to use format avif, while for the second source it’s webp, and for the fallback img it’s jpg.
Check the rendered image in a browser to confirm that the modern formats are being used.
I’ll DRY-up that HTML into an 11ty shortcode in due course.
I’ve no doubt that I’ll be getting some of this wrong – this stuff gets pretty complicated! For example I note my image file size is still quite large so I wonder if I should be manually creating the avif and webp versions in Squoosh myself to ensure getting the savings that make this approach worthwhile, rather than handing the conversion off to Cloudinary. (However this would mean having to host more images…)
In the meantime however, I’m happy that this approach has simplified the mental overhead of handling modern, responsive blog images, and optimising it can be a work in progress.
Yesterday I read Eric Meyer discussing CSS Cascade Layers and commenting that the speed at which it had transitioned from first public working draft to shipping as a full public release in every major desktop and mobile browser had made his head spin. Amazing stuff and an indicator of the turbo-boosted pace at which modern CSS is now evolving.
It also made me want to properly read up on Cascade Layers, because I knew some of the theory but now wanted to consider using it in practice. I’m no great fan of “cascade-taming” CSS frameworks like BEM and SUIT (although I acknowledge why we have them) so I’m interested to know if Cascade Layers can replace them. Stephanie Eckles’ article is an excellent primer.
I liked the idea of a specifying a stack like this:
@layer reset, base, theme, components, utilities;
You can then write styles into any of those layers at any point in a stylesheet, safe in the knowledge that the original stack definition sets the order of priority rather than the sequence in which we wrote specific styles.
Stephanie also addresses the question of whether we should write every component as a layer, which is something I’ve been considering. She advises that you could… but it’s probably not going to achieve the scoping effect that you want.
layers are not intended to solve scoping or encapsulation of styles. For that, keep an eye on another spec also being authored by Miriam Suzanne for actual native CSS scoping.
Lastly, Stephanie tackles how ready Cascade Layers are to use right now. At the time she wrote the article – January 2022 – the feature wasn’t widely supported, so wasn’t an option. Additionally Cascade Layers can’t really be used as a progressive enhancement because its nature is so all-encompassing and because testing for feature support using @supports isn’t an option.
However like Eric Meyer mentions, a few months is a long time in CSS support! And as I write in June 2022 the browser support picture is currently looking quite healthy. However given that the first browsers to add support were only released a few months ago in February or March of this year, I think we might need to wait a bit longer – maybe til the percentage of users on non-supporting browsers is negligible – before using this on larger, higher-traffic sites.
Nothing to stop us experimenting on our smaller and intranet-based sites, though!
At work I have to think about complex HTML tables a lot. The challenge with doing tables well is that 99% of online table tutorials use fairly simple examples… whereas in reality design and product teams often want to squeeze in lots more. It’s really hard to balance those needs against accessibility, systemisation, styling and responsiveness.
Heads up: I’ve published this post early while it’s still a work in progress because it’s better for me to have it available for reference than languishing in drafts and forgotten. Apologies if you read it in a temporarily rough state.
Following a lot of work on tables I’ve recently gained additional insight into the possibilities and constraints, thanks to an accessibility review by Tetralogical and some great articles by Adrian Roselli.
Here are my new rules of thumb.
Avoid complex recreations of tables with alternate elements
In addition to developing a component wrapping the HTML table element to handle simple data tables, I recently created an alternate component for “tables with bells and whistles”. It used a combination of the HTML description list element plus CSS Grid plus some display: contents in lieu of the currently poorly supported subgrid. This approach allowed recreating a table-like appearance but facilitating much more responsive layout flexibility, amongst other benefits.
Unfortunately this resulted in an accessibiliy fail around using the description list in this way. Popular combinations of browsers and assistive technologies do not support description lists sufficiently to convey the intended crucial relationships between the faux table headers and faux table cells.
ARIA Grid role: an alternative in theory (if not in practice)
I noted that Github handle their “repository directory indexes” using the ARIA grid role. Their HTML is like this (I’ve abbreviated it a touch):
<divrole="grid"aria-labelledby="files"class="…"><divclass="sr-only"role="row"><divrole="columnheader">Type</div><divrole="columnheader">Name</div><divrole="columnheader"class="d-none d-md-block">Latest commit message</div><divrole="columnheader">Commit time</div></div><!-- interesting 'fake' row here --><divrole="row"class="…"><divrole="rowheader"class="…"><arel="nofollow"title="Go to parent directory"class="…"href="…"><spanclass="…"style="…">. .</span></a></div><divrole="gridcell"class="…"></div><divrole="gridcell"></div></div><!-- first real row --><divrole="row"class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item navigation-focus"><divrole="gridcell"class="…"><svg…></svg></div><divrole="rowheader"class="…"><spanclass="…"><aclass="…"href="…">my-file-name.md</a></span></div><divrole="gridcell"class="…"><spanclass="…"><ahref="…">The commit message</a></span></div><divrole="gridcell"class="…"><time-agodatetime="2021-06-17T16:45:42Z">11 months ago</time-ago></div></div><!-- more rows go here --></div>
I like the idea of looking at alternatives to tables but don’t think I’d take this approach right now. Where there are lots of focusable elements it turns those multiple tab-stops into one (the grid is a single widget) which is perhaps useful for some cases, but I’ve yet to encounter them. It’d also require you to do manual focus management within the widget.
It’s an interesting approach though, and one I’ll keep in the back of my mind.
You can achieve “bells and whistles” within a table accessibly
Here are some handy techniques – done accesibly – courtesy of Adrian Roselli:
Responsive accessible tables – this more complex approach employs JavaScript to i) apply appropriate ARIA roles to existing table HTML, and ii) create clever alternate labelling using pseudo elements. It uses CSS to change the display of the table and its children to create a small-screen-friendly layout. The JS-applied roles serve to maintain the necessary semantics that would otherwise be lost when applying the radical CSS changes.
Charlie Cathcart’s responsive table is similar to the above although perhaps less comprehensive. However it might have other interesting aspects.
A while back I bookmarked Michelle Barker’s CSS Grid based overlay technique which neatly allows layering one element atop another using CSS Grid rather than absolute positioning. Now, Stephanie Eckles has taken the idea a step further with her Smol Stack Layout which offers a more flexible markup structure, some intuitive grid area naming and a neat aspect-ratio API.
Stephanie’s component is feature-packed and opinionated to the extent that it took me a while to understand all the moving parts. So for simplicity I’ve created a pared-back version on CodePen: see Layering utility with CSS Grid.
While Michelle’s utility kept the markup really simple with the container doubling-up as the first visual “layer in the cake”, I think for flexibility and robustness I prefer Stephanie’s approach where the container only serves to set the aspect ratio, with the layers represented by two or more child elements.
Layering text upon images
In Smol background picture, Stephanie goes further, leaning on her layering utility to cleverly layer text upon images. This is a modern alternative to the type of effect we previously achieved with background images. It uses a content image marked up using <picture> to progressively enhance the format (heavier-weight jpg for old browsers, lightweight webp for new browsers) and is styled with object-fit: cover in order to perfectly span its container.
This modern approach is great because often from an accessibility perspective our background images should really be content, described properly with alt, to provide equivalent visual and non-visual experiences. Furthermore using a content image tends to be better for performance with there now being so many new image techniques and attributes at our disposal when compared to background images. Lastly, handling the image as content makes it more flexible for styling.
Using Grid for a “Hero” Banner
Another noteworthy member of this family of techniques from Stephanie is her Hero with CSS Grid. Here she uses the same idea of a single grid-template-area with child content and image stacked up in layers, alongside some nifty use of grid positioning properties to align elements within that. This one is very flexible, very responsive, and super-useful.
Summing up
I really like this move away from absolute positioning because it always felt brittle. It doesn’t play well with responsive layouts, and isn’t resilient to cases where adjacent elements could overlap. Furthermore you often see absolute positioning used in conjunction with pseudo elements and while I’ve occasionally taken this approach (and appreciate the creativity behind these techniques) I’ll admit I find it much easier to read and maintain CSS that relates to actual structural elements rather than “magical” CSS elements. I much prefer these simple, modern and fit-for-purpose CSS Grid based approaches.
I recorded a talk on “Hiding elements on the web” for @freeagent’s tech blog. It’s a tricky #FrontEnd & #a11y topic so I try to cover some good practices and responsible choices. Hope it helps someone. (Also it’s my first video. Lots of room to improve!)
After a couple of years of reading about web components (and a lot of head-scratching), I’ve finally got around to properly creating one… or at least a rough first draft!
I haven’t yet tried writing tests for a web component
I should find out how to refer to the custom element name in JavaScript without repeating it
I should look into whether observedAttributes and attributeChangedCallback are more appropriate than the more typical event listeners I used
References
I found Eric Bidelman’s article Custom Elements v1: Reusable Web Components pretty handy. In particular it taught me how to create a <template> including a <slot> to automatically ringfence the Light DOM content, and then to attach that template to the Shadow DOM to achieve my enhanced component.
Browser devtools have made redesigning a site such a pleasure. I love writing and adjusting a CSS file right in the sources panel and seeing design changes happen as I type, and saving it back to the file. (…) Designing against live HTML allows happy accidents and discoveries to happen that I wouldn't think of in an unconstrained design mockup
I feel very late to the party here. I tend to tinker in the DevTools Element Styles panel rather than save changes. So, inspired by Scott, I’ve just tried this out on my personal website. Here’s what I did.
started up my 11ty-based site locally which launches a localhost URL for viewing it in the browser;
opened Chrome’s DevTools at Sources;
checked the box “Enable local overrides” then followed the prompts to allow access to the folder containing my SCSS files;
opened an SCSS file in the Sources tab for editing side-by-side with my site in the browser;
made a change, hit Cmd-S to save and marvelled at the fact that this updated that file, as confirmed by a quick git status check.
switched to the Elements panel, opened its Styles subpanel, made an element style change there too, then confirmed that this alternative approach also saves changes to a file.
This is a really interesting and efficient way of working in the browser and I can see me using it.
There are also a couple of challenges which I’ll probably want to consider. Right now when I make a change to a Sass file, the browser takes a while to reflect that change, which diminishes the benefit of this approach. My site is set up such that Eleventy watches for changes to the sass folder as a trigger for rebuilding the static site. This is because for optimal performance I’m purging the compiled and combined CSS and inlining that into the <head> of every file… which unfortunately means that when the CSS is changed, every file needs rebuilt. So I need to wait for Eleventy to do its build thing until the page I’m viewing shows my CSS change.
To allow my SCSS changes to be built and reflected faster I might consider no longer inlining CSS, or only inlining a small amount of critical stuff… or maybe (as best of all worlds) only do the inlining for production builds but not in development. Yeah, I like that latter idea. Food for thought!
“Dark mode” has been a buzz-phrase in web development since around 2019. It refers to the ability provided by modern operating systems to set the user interface’s appearance to either light or dark. Web browsers and technologies support this by allowing developers to detect whether or not the OS provides such settings, and if so which mode the user prefers. Developers can create alternate light and dark themes for their websites and switch between these intelligently (responsively?) to fit with the user’s system preference.
I’ve been meaning to do some work on this front for a while and finally got around to it. (You might even be reading this post with your computer’s dark colour scheme enabled and seeing the fruits of my labour.) Here’s how I set things up and the lessons I learned along the way.
Switching your computer’s appearance
On a Mac:
System Preferences > General > Appearance
On Windows:
Colors > Choose your color
On iOS:
Settings > Display & Brightness > Appearance
On Android:
Settings > Dark Theme
Emulating this in browser DevTools
In Chromium-based browsers you can open DevTools, then open the Rendering tool (which might be hidden behind More Tools). In the Emulate CSS media feature prefers-color-scheme dropdown, select prefers-color-scheme: dark or prefers-color-scheme: light.
The theme-color HTML meta tag
You can use the theme-color HTML meta tag to indicate to the browser a colour it can use to customise the display of the page and surrounding elements such as the address bar. The reason we have a meta tag solution to this rather than leaving it to CSS is performance; it allows the browser to make the relevant updates immediately.
In practice you might specify your “highlight colour”—Clearleft currently use their signature green. Alternatively you could specify both your light theme and dark theme background colours, using the media attribute to associate each with the user colour scheme preference it is optimised for. This is the approach I chose.
<!-- Set theme color to white when user prefers light mode --><metaname="theme-color"content="rgb(255,255,255)"media="(prefers-color-scheme: light)"><!-- Set theme color to a custom black when user prefers dark mode --><metaname="theme-color"content="rgb(38,38,38)"media="(prefers-color-scheme: dark)">
This had me considering PWA matters again for the first time in a while. I previously definined a PWA “theme colour” for my website in my manifest.manifest file. However unlike in the theme-color meta tag approach, the manifest allows defining one theme colour only. While I don’t think there’d be any issue in having both the meta tag and manifest value in play simultaneously (my understanding is that the HTML would take priority over the manifest), I decided to keep things simple and removed theme_color from my manifest file for now.
The color-scheme meta tag is used to specify one or more color schemes/modes with which the page is compatible. Unlike theme-color you don’t provide an arbitrary colour value, but rather one of light or dark or both in combination. This tells the browser whether it can change default background, foreground and text colours to match the current system appearance. As Jim Nielsen notes in Don’t forget the color-scheme property, it gives the browser permission to automatically change standard form controls, scroll bars, and other named system colors.
I include this meta tag on each page (just after my theme-color meta tags). I indicate that my styles have been prepped to handle the browser applying either light or dark colour schemes and—via the order of values in the content attribute—that I prefer light.
There is also a color-scheme CSS property, which I’ll come to later. Once again though, having an HTML meta tag helps browsers to apply things faster;
although I’m currently intimating that I prefer light, in future I might update this to dark first (assuming I don’t hear of any reasons against it). The dark colour palette is really growing on me!
Ensuring colours are accessible
While working on a new dark colour palette and tweaking my light palette I made sure to check that colour contrast met accessibility requirements.
Useful tools on this front include:
Activating Chrome’s element inspector (the “box with arrow at bottom-right” icon) enables hovering an element to check the contrast of text against background;
Erik Kennedy’s Accessible Color Generator provides slightly modified colour alternatives when contrast is insufficient—really handy and I used this a couple of times;
Are my colors accessible? is another great “check contrast, digest results, then tweak” tool which provides more detailed information than the Chrome inspector, especially regarding the impact of small text on contrast.
Design Tokens
It quickly became clear that I’d need global colour settings that I could use across multiple technologies and multiple files. For example, I’d want to reuse the same custom background colour value in an HTML theme-color meta tag, in CSS, and perhaps also in a JSON-based manifest file.
I created _data/tokens.json in which I defined raw tokens such as colorDark, colorDarker and colorLight.
Then in my Nunjucks-based HTML templates I could access that token data to define meta tag values using {{ tokens.colorLight }}. These values would be interpolated to the real CSS colour values during build.
I also created a new Nunjucks file, theme_css.njk, adding permalink: "css/theme.css" in its frontmatter so that it’d generate a CSS file. This file maps my design tokens to custom properties set on the root element, something like this:
Using custom properties allowed me to do the hard work of preparing my light and dark themes upfront and removed the need to constantly duplicate values and write code forks throughout my CSS.
Having previously created a base layer of reusable custom property representations of my design tokens, I began creating more specific custom properties to serve different contexts.
The color-scheme property allows us to specify one or more colour schemes/modes with which an element is compatible. I’m defining it on the root element i.e. for the whole page. My approach was to start by specifying support for a light colour scheme only, then define background and text colour custom properties with values optimised for light colour scheme.
Using @media (prefers-color-scheme: dark) {…} we can check the user’s colour scheme preference. When the user prefers dark, I change color-scheme to dark to let the browser do its “set sensible defaults” thing, and I update the custom property values to those optimised to blend with a dark appearance.
The reusable, theme-sensitive custom properties I’ve plumped for are:
highlight colour: really just my brand colour, although lightened a touch in dark mode for better contrast;
page background colour;
“band” background colour: something I’d use as a band of alternative background colour to distinguish special sections like the header or footer;
ink colour: my default text colour;
“offset” ink colour: a grey for little bits of meta text like dates and categories.
I’m sure I’ll evolve these over time.
Lastly, the accent-colour CSS property is used by some form controls e.g. radios and checkboxes. I set that to my highlight colour with the intention of creating a more branded experience.
SVG considerations
My SVG-based logo didn’t look right in dark mode, however the fix was pretty simple. I applied BEM-style element classes to any problematic path elements of the SVG then wrote CSS for those. The CSS tests for prefers-color-scheme: dark and updates the path’s fill or stroke colour as necessary.
What about leaving everything to the browser?
Having read Jim Nielsen’s brilliant article on CSS System Colors I tried feeding the browser color-scheme: light dark, removing my arbitrary dark theme colours, and leaving the colour palette entirely up to the browser. Along the way I learned some interesting lessons on system colours—which we can also choose to use as valid CSS colours in our custom components—such as Canvas and CanvasText.
I love this idea in principle! However in practice:
only Safari’s colour palette looks consistent with the rest of the Mac OS. The palette applied by Chrome doesn’t; it has its own, different “black”. So for the control you’ve given away, you don’t necessarily achieve that nice “consistency with the OS” reward in return;
as far as I know you can’t lighten or darken the system colours so it’s hard to create a multi-tone, complimentary palette, and also be confident in achieving sufficient colour contrast. That’s fine if you only need a single background colour for the entire page with no alternate bands of colour (like on Jim’s blog) however I think that’s a little restrictive. (Maybe I’m getting too hung up on control here though, and introducing additional arbitrary colours would work fine alongside a variable “system black”);
Firefox and iOS Safari are a little problematic in their support for the technologies involved, leading to writing a few hacky workarounds.
For the combined reasons above I’m sticking with manually defined colours for now (however I have a pull request I can revisit later if the mood takes).
What could I do better?
With extra time, I might:
think more deeply about dark theme design, perhaps following some of the tips regarding shadows, depth and colour contrast in CSS Tricks’ A complete guide to dark mode on the web;
consider providing a theme switcher control to allow the user to choose the website theme they want regardless of the current OS appearance. (But I probably won’t; I’m not sure it’s necessary)
References
Theming, from Jeremy Keith’s excellent Learn Responsive Design
Great tutorial (with accompanying video) from Adam Argyle which starts with a useful definition of what a Toast is and is not:
Toasts are non-interactive, passive, and asynchronous short messages for users. Generally they are used as an interface feedback pattern for informing the user about the results of an action. Toasts are unlike notifications, alerts and prompts because they're not interactive; they're not meant to be dismissed or persist. Notifications are for more important information, synchronous messaging that requires interaction, or system level messages (as opposed to page level). Toasts are more passive than other notice strategies.
There are some important distinctions between toasts and notifications in that definition: toasts are for less important information and are non-interactive. I remember in a previous work planning exercise regarding a toast component a few of us got temporarily bogged down in working out the best JavaScript templating solution for SVG icon-based “Dismiss” buttons… however we were probably barking up the wrong tree with the idea that toasts should be manually dismissable.
There are lots of interesting ideas and considerations in Adam’s tutorial, such as:
using the <output> element for each toast
some crafty use of CSS Grid and logical properties for layout
combining hsl and percentages in custom properties to proportionately modify rather than redefine colours for dark mode
animation using keyframes and animation
native JavaScript modules
inserting an element before the <body> element (TIL that this is a viable option)
Warning: this entry is a work-in-progress and incomplete. That said, it's still a useful reference to me which is why I've published it. I’ll flesh it out soon!
There are lots of different strands of web development. You try your best to be good at all of them, but there’s only so much time in the day! Animation is an area where I know a little but would love to know more, and from a practical perspective I’d certainly benefit from having some road-ready solutions to common challenges. As ever I want to favour web standards over libraries where possible, and take an approach that’s lean, accessible, progressively-enhanced and performance-optimised.
Here’s my attempt to break down web animation into bite-sized chunks for ocassional users like myself.
Defining animation
Animation lets us make something visually move between different states over a given period of time.
Benefits of animation
Animation is a good way of providing visual feedback, teaching users how to use a part of the interface, or adding life to a website and making it feel more “real”.
Simple animation with transition properties
CSS transition is great for simple animations triggered by an event.
We start by defining two different states for an element—for example opacity:1 and opacity:0—and then transition between those states.
The first state would be in the element’s default styles (either as explicitly-defined property values or existing implicitly based on property defaults) and the other in either its :hover or :focus styles or in a class applied by JavaScript following an event.
Without the transition the state change would still happen but would be instantaneous.
You’re not limited to only one property being animated and might, for example, transition between different opacity and transform states simultaneously.
Here’s an example “rise on hover” effect, adapted from Stephanie Eckles’s Smol CSS.
using custom properties makes it really easy to transition a different property than transform without writing repetitious CSS.
we have a parent and child (<div> and <span> respectively in this example) allowing us to avoid the accidental flicker which can occur when the mouse is close to an animatable element’s border by having the child be the effect which animates when the trigger (the parent) is hovered.
Complex animations with animation properties
If an element needs to animate automatically (perhaps on page load or when added to the DOM), or is more complex than a simple A to B state change, then a CSS animation may be more appropriate than transition. Using this approach, animations can:
run automatically (you don’t need an event to trigger a state change)
go from an initial state through multiple intermediate steps to a final state rather than just from state A to state B
run forwards, in reverse, or alternate directions
loop infinitely
The required approach is:
use @keyframes to define a reusable “template” set of animation states (or frames); then
apply animation properties to an element we want to animate, including one or more @keyframes to be used.
Note that you can also opt to include just one state in your @keyframes rule, usually the initial state (written as either from or 0%) or final state (written as either to or 100%). You’d tend to do that for a two-state animation where the other “state” is in the element’s default styles, and you’d either be starting from the default styles (if your single @keyframes state is to) or finishing on them (if your single @keyframes state is from).
Should I use transition or animation?
As far as I can tell there’s no major performance benefit of one over the other, so that’s not an issue.
When the animation will be triggered by pseudo-class-based events like :hover or :focus and is simple i.e. based on just two states, transition feels like the right choice.
Beyond that, the choice gets a bit less binary and seems to come down to developer preference. But here are a couple of notes that might help in making a decision.
For elements that need to “animate in” on page load such as an alert, or when newly added to the DOM such as items in a to-do list, an animation with keyframes feels the better choice. This is because transition requires the presence of two CSS rules, leading to dedicated JavaScript to grab the element and apply a class, whereas animation requires only one and can move between initial and final states automatically including inserting a delay before starting.
For animations that involve many frames; control over the number of iterations; or looping… use @keyframes and animation.
For utility classes and classes that get added by JS to existing, visible elements following an event, either approach could be used. Arguably transition is the slightly simpler and more elegant CSS to write if it covers your needs. Then again, you might want to reuse the animations applied by those classes for both existing, visible elements and new, animated-in elements, in which case you might feel that instead using @keyframes and animation covers more situations.
Performance
A smooth animation should run at 60fps (frames per second). Animations that are too computationally expensive result in frames being dropped, i.e. a reduced fps rate, making the animation appear janky.
Cheap and slick properties
The CSS properties transform and opacity are very cheap to animate. Also, browsers often optimise these types of animation using hardware acceleration. To hint to the browser that it should optimise an animation property (and to ensure it is handled by the GPU rather than passed from CPU to GPU causing a noticeable glitch) we should use the CSS will-change property.
.my-element{will-change: transform;}
Expensive properties
CSS properties which affect layout such as height are very expensive to animate. Animating height causes a chain reaction where sibling elements have to move too. Use transform over layout-affecting properties such as width or left if you can.
Some other CSS properties are less expensive but still not ideal, for example background-color. It doesn't affect layout but requires a repaint per frame.
Test your animations on a popular low-end device.
Timing functions
linear goes at the same rate from start to finish. It’s not like most motion in the real world.
ease-out starts fast then gets really slow. Good for things that come in from off-screen, like a modal dialogue.
ease-in starts slow then gets really fast. Good for moving somethng off-screen.
ease-in-out is the combination of the previous two. It‘s symmetrical, having an equal amount of acceleration and deceleration. Good for things that happen in a loop such as element fading in and out.
ease is the default value and features a brief ramp-up, then a lot of deceleration. It’s a good option for most general case motion that doesn’t enter or exit the viewport.
Practical examples
You can find lots of animation inspiration in libraries such as animate.css (and be sure to check animate.css on github where you can search their source for specific @keyframe animation styles).
But here are a few specific examples of animations I or teams I’ve worked on have had to implement.
Skip to content
The anchor’s State A sees its position fixed—i.e. positioned relative to the viewport—but then moved out of sight above it via transform: translateY(-10em). However its :focus styles define a State B where the intial translate has been undone so that the link is visible (transform: translateY(0em)). If we transition the transform property then we can animate the change of state over a chosen duration, and with our preferred timing function for the acceleration curve.
HTML:
<divclass="u-visually-hidden-until-focused"><ahref="#skip-link-target"class="u-visually-hidden-until-focused__item">Skip to main content</a></div><nav><ul><li><ahref="/">Home</a></li><li><ahref="/">News</a></li><li><ahref="/">About</a></li><!-- …lots more nav links… --><li><ahref="/">Contact</a></li></ul></nav><mainid="skip-link-target"><h1>This is the Main content</h1><p>Lorem ipsum <ahref="/news/">dolor sit amet</a> consectetur adipisicing elit.</p><p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p></main>
For this requirement we want an element to animate from invisible to visible on page load. I can imagine doing this with an image or an alert, for example. This is pretty straightforward with CSS only using @keyframes, opacity and animation.
Stephanie Eckles shared a great CSS-only solution for animating in a newly added element which handily includes a Codepen demo. She mentions “CSS-only” because it’s common for developers to achieve the fancy animation via transition but that means needing to “make a fake event” via a JavaScript setTimeout() so that you can transition from the newly-added, invisible and class-free element state to adding a CSS class (perhaps called show) that contains the opacity:1, fancy transforms and a transition. However Stephanie’s alternative approach combines i) hiding the element in its default styles; with ii) an automatically-running animation that includes the necessary delay and also finishes in the keyframe’s single 100% state… to get the same effect minus the JavaScript.
Avoiding reliance on JS and finding a solution lower down the stack is always good.
HTML:
<button>Add List Item</button><ul><li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum facilis perspiciatis dignissimos, et dolores pariatur.</li></ul>
CSS:
li{animation: show 600ms 100ms cubic-bezier(0.38, 0.97, 0.56, 0.76) forwards;
// Prestate
opacity: 0;
// remove transform for just a fade-in
transform:rotateX(-90deg);transform-origin: top center;}@keyframes show{100%{opacity: 1;transform: none;}}
Jhey Tompkins shared another CSS-only technique for adding elements to the DOM with snazzy entrance animations. He also uses just a single @keyframes state but in his case the from state which he uses to set the element’s initial opacity:0, then in his animation he uses an animation-fill-mode of both (rather than forwards as Stephanie used).
I can’t profess to fully understand both however if you change Jhey’s example to use forwards instead, then the element being animated in will temporarily appear before the animation starts (which ain’t good) rather than being initially invisible. Changing it to backwards gets us back on track, so I guess the necessary value relates to whether you’re going for from/0% or to/100%… and both just covers you for both cases. I’d probably try to use the appropriate one rather than both just in case there’s a performance implication.
Animated disclosure
Here’s an interesting conundrum.
For disclosure (i.e. collapse and expand) widgets, I tend to either use the native HTML <details> element if possible or else a simple, accessible DIY disclosure in which activating a trigger toggles a nearby content element’s visibility. In both cases, there’s no animation; the change from hidden to revealed and back again is immediate.
To my mind it’s generally preferable to keep it simple and avoid animating a disclosure widget. For a start, it’s tricky! The <details> element can’t be (easily) animated. And if using a DIY widget it’ll likely involve animating one of the expensive properties. Animating height or max-height is also gnarly when working with variable (auto) length content and often requires developers to go beyond CSS and reach for JavaScript to calculate computed element heights. Lastly, forgetting the technical challenges, there’s often no real need to animate disclosure; it might only hinder rather than help the user experience.
Animate the <details> element. This is a nice, standards-oriented approach. But it might only be viable for when you don’t need to mess with <details> appearance too much. We’d struggle to apply very custom styles, or to handle a “show the first few list items but not all” requirement like in the BBC Sounds example;
Animate CSS Grid. This is a nice idea but for now the animation only works in Firefox*. It’d be great to just consider it a progressive enhancement so it just depends on whether the animation is deemed core to the experience;
Animate from a max-height of 0 to “something sufficient” (my pen is inspired by Scott O’Hara’s disclosure example). This is workable but not ideal; you kinda need to set a max-height sweetspot otherwise your animation will be delayed and too long. You could of course add some JavaScript to get the exact necessary height then set it. BBC use max-height for their tracklist animation and those tracklists likely vary in length so I expect they use some JavaScript for height calculation.
Accessibility and animation can co-exist, as Cassie Evans explains in her CSS-Tricks article Empathetic Animation. We should consider which parts of our website are suited to animation (for example perhaps not on serious, time-sensitive tasks) and we can also respect reduced motion preferences at a global level or in a more finer-grained way per component.
Notes
transition-delay can be useful for avoiding common annoyances, such as when a dropdown menu that appears on hover disappears when you try to move the cursor to it.
Just taking a moment for some musings on which way the front-end wind is blowing (from my perspective at least) and how that might practically impact my approach on the next small-ish website that I code.
I might lean into HTTP2
Breaking CSS into small modules then concatenating everything into a single file has traditionally been one of the key reasons for using Sass, but in the HTTP2 era where multiple requests are less of a performance issue it might be acceptable to simply include a number of modular CSS files in the <head>, as follows:
The same goes for browser-native JavaScript modules.
This isn’t something I’ve tried yet and it’d feel like a pretty radical departure from the conventions of recent years… but it‘s an option!
I’ll combine ES modules and classes
It’s great that JavaScript modules are natively supported in modern browsers. They allow me to remove build tools, work with web standards, and they perform well. They can also serve as a mustard cut that allows me to use other syntax and features such as async/await, arrow functions, template literals, the spread operator etc with confidence and without transpilation or polyfilling.
In the <head>:
<scripttype="module"src="/js/main.js"></script>
In main.js
import { Modal } from '/components/modal.js';
const Modal = new Modal();
modal.init();
I’ve done a lot of preparatory reading and learning about web components in the last year. I’ll admit that I’ve found the concepts (including Shadow DOM) occasionally tough to wrap my head around, and I’ve also found it confusing that everyone seems to implement web components in different ways. However Dave Rupert’s HTML with Superpowers presentation really helped make things click.
I’m now keen to create my own custom elements for javascript-enhanced UI elements; to give LitElement a spin; to progressively enhance a Light DOM baseline into Shadow DOM fanciness; and to check out how well the lifecycle callbacks perform.
I’ll go deeper with custom properties
I’ve been using custom properties for a few years now, but at first it was just as a native replacement for Sass variables, which isn’t really exploiting their full potential. However at work we’ve recently been using them as the special sauce powering component variations (--gap, --mode etc).
In our server-rendered components we’ve been using inline style attributes to apply variations via those properties, and this brings the advantage of no longer needing to create a CSS class per variation (e.g. one CSS class for each padding variation based on a spacing scale), which in turn keeps code and specificity simpler. However as I start using web components, custom properties will prove really handy here too. Not only can they be updated by JavaScript, but furthermore they provide a bridge between your global CSS and your web component because they can “pierce the Shadow Boundary”, make styling Shadow DOM HTML in custom elements easier.
I’ll use BEM, but loosely
Naming and structuring CSS can be hard, and is a topic which really divides opinion. Historically I liked to keep it simple using the cascade, element and contextual selectors, plus a handful of custom classes. I avoided “object-oriented” CSS methodologies because I found them verbose and, if I’m honest, slightly “anti-CSS”. However it’s fair to say that in larger applications and on projects with many developers, this approach lacked a degree of structure, modularisation and predictability, so I gravitated toward BEM.
BEM’s approach is a pretty sensible one and, compared to the likes of SUIT, provides flexibility and good documentation. And while I’ve been keeping a watchful eye on new methodologies like CUBE CSS and can see that they’re choc-full of ideas, my feeling is that BEM remains the more robust choice.
It’s also important to me that BEM has the concept of a mix because this allows you to place multiple block classes on the same element so as to (for example) apply an abstract layout in combination with a more implementation-specific component class.
<div class="l-stack c-news-feed">
Where I’ll happily deviate from BEM is to favour use of certain ARIA attributes as selectors (for example [aria-current=page] or [aria-expanded=true] because this enforces good accessibility practice and helps create equivalence between the visual and non-visual experience. I’m also happy to use the universal selector (*) which is great for owl selectors and I’m fine with adjacent sibling (and related) selectors.
Essentially I’m glad of the structure and maintainability that BEM provides but I don’t want a straitjacket that stops me from using my brain and applying CSS properly.
Jeremy Keith’s new course for Google’s web.dev learning platform is fantastic and covers a variety of aspects of responsive design including layout (macro and micro), images, icons and typography.
A designer colleague recently asked me what course or resources I would recommend for learning front-end web development. She mentioned React at the beginning but I suggested that it’d be better to start by learning HTML, CSS, and JavaScript. As for React: it’s a subset or offshoot of JavaScript so it makes sense to understand vanilla JS first.
For future reference, here are my tips.
Everything in one place
Google’s web.dev training resource have also been adding some excellent guides, such as:
Another great one-stop shop is MDN Web Docs. Not only is MDN an amazing general quick reference for all HTML elements, CSS properties, JavaScript APIs etc but for more immersive learning there are also MDN’s guides.
Pay attention to HTML
One general piece of advice is that when people look at lists of courses (whether or not they are new to web development) they ensure to learn HTML. People tend to underestimate how complicated, fast-moving and important HTML is.
Also, everything else – accessibility, CSS, JavaScript, performance, resilience – requires a foundation of good HTML. Think HTML first!
Learning CSS, specifically
CSS is as much about concepts and features – e.g. the cascade and specificity, layout, responsive design, typography, custom properties – as it is about syntax. In fact probably more so.
Most tutorials will focus on the concepts but not necessarily so much on practicalities like writing-style or file organisation.
Google’s Learn CSS course should be pretty good for the modern concepts.
If you’re coming from a kinda non-CSS-oriented perspective, Josh W Comeau’s CSS for JavaScript Developers (paid course) could be worth a look.
If you prefer videos, you could check out Steve Griffith’s video series Learning CSS. Steve’s videos are comprehensive and well-paced. It contains a whole range of topics (over 100!), starting from the basics like CSS Box Model.
In terms of HTML and CSS writing style (BEM etc) and file organisation (ITCSS etc), here’s a (version of a) “style guide” that my team came up with for one of our documentation websites. I think it’s pretty good!
CSS and HTML Style Guide (to do: add link here)
For more on ITCSS and Harry Roberts’s thoughts on CSS best practices, see:
Resilient Web Design by Jeremy Keith. A fantastic wide-screen perspective on what we’re doing, who we’re doing it for, and how to go about it. Read online or listen as an audiobook.
Inclusive Components by Heydon Pickering. A unique, accessible approach to building interactive components, from someone who’s done this for BBC, Bulb, Spotify.
Every Layout by Heydon Pickering & Andy Bell. Introducing layout primitives, for handling responsive design in Design Systems at scale (plus so many insights about the front-end)
Atomic Design by Brad Frost. A classic primer on Design Systems and component-composition oriented thinking.
Practical SVG by Chris Coyier. Learn why and how to use SVG to make websites more aesthetically sharp, performant, accessible and flexible.
Web Typography by Richard Rutter. Elevate the web by applying the principles of typography via modern web typography techniques.
On the web buttons and links are fundamentally different materials. However some design and development practices have led to them becoming conceptually “bundled together” and misunderstood. Practitioners can fall into the trap of seeing the surface-level commonality that “you click the thing, then something happens” and mistakenly thinking the two elements are interchangeable. Some might even consider them as a single “button component” without considering the distinctions underneath. However this mentality causes our users problems and is harmful for effective web development. In this post I’ll address why buttons and links are different and exist separately, and when to use each.
Problematic patterns
Modern website designs commonly apply the appearance of a button to a link. For isolated calls to action this can make sense however as a design pattern it is often overused and under-cooked, which can cause confusion to developers implementing the designs.
Relatedly, it’s now common for Design Systems to have a Button component which includes button-styled links that are referred to simply as buttons. Unless documented carefully this can lead to internal language and comprehension issues.
Meanwhile developers have historically used faux links (<a href="#">) or worse, a DIY clickable div, as a trigger for JavaScript-powered functionality where they should instead use native buttons.
These patterns in combination have given rise to a collective muddle over buttons and links. We need to get back to basics and talk about foundational HTML.
Buttons and anchors in HTML
There are two HTML elements of interest here.
Hyperlinks are created using the HTML anchor element (<a>). Buttons (by which I mean real buttons rather than links styled to appear as buttons) are implemented with the HTML button element (<button>).
normally links to another document (i.e. page) on the current website or on another website
can alternatively link to a different section of the same page
historically and by default appears underlined
when hovered or focused offers visual feedback from the browser’s status bar
uses the “pointing hand” mouse pointer
results in browser making an HTTP GET request by default. It’s intended to get a page or resource rather than to change something
offers specific right-click options to mouse users (open in new tab, copy URL, etc)
typically results in an address which can be bookmarked
can be activated by pressing the return key
is announced by screen readers as “Link”
is available to screen reader users within an overall Links list
A button…
does something (i.e. performs an action, such as “Add”, “Update” or "Show")
can be used as <button type=submit> within a form to submit the form. This is a modern replacement for <input type=submit /> and much better as it’s easier to style, allows nested HTML and supports CSS pseudo-elements
can be used as <button type=button> to trigger JavaScript. This type of button is different to the one used for submitting a <form>. It can be used for any type of functionality that happens in-place rather than taking the user somewhere, such as expanding and collapsing content, or performing a calculation.
historically and by default appears in a pill or rounded rectangle
can be extended with further ARIA button-related states like aria-pressed
is announced by screen readers as “Button”
unlike a link is not available to screen reader users within a dedicated list
Our responsibilities
It’s our job as designers and developers to use the appropriate purpose-built element for each situation, to present it in a way that respects conventions so that users know what it is, and to then meet their expectations of it.
Tips
Visually distinguish button-styled call-to-action links from regular buttons, perhaps with a more pill-like appearance and a right-pointing arrow
Avoid a proliferation of call-to-action links by linking content itself (for example a news teaser’s headline). Not only does this reduce “link or button?” confusion but it also saves space, and provides more accessible link text.
Consider having separate Design System components for Button and ButtonLink to reinforce important differences.
For triggering JavaScript-powered interactions I’ll typically use a button. However in disclosure patterns where the trigger and target element are far apart in the DOM it can make sense to use a link as the trigger.
For buttons which are reliant on JavaScript, it’s best to use them within a strategy of progressive enhancement and not render them on the server but rather with client-side JavaScript. That way, if the client-side JavaScript is unsupported or fails, the user won’t be presented with a broken button.
Update: 23 November 2024
Perhaps a better heuristic than David MacDonald’s mentioned above, is:
What I prefer about including a resource is that the “goes somewhere” definition of a link breaks down for anchors that instruct the linked resource to download (via the download attribute) rather than render in the browser, but this doesn’t. I also like the inclusion of simple because some buttons (like the submit button of a search form) might finish by taking you to a resource (the search results page) but that’s a complex action not a simple connection; you’re searching a database using your choice of search query.
Here’s a great new presentation by Dave Rupert (of the Shop Talk show) in which he makes a compelling case for adopting Web Components. Not only do they provide the same benefits of encapsulation and reusability as components in proprietary JavaScript frameworks, but they also bring the reliability and portability of web standards, work without build tools, are suited to progressive enhancement, and may pave the way for a better web.
Dave begins by explaining that Web Components are based on not just a set of technologies but a set of standards, namely:
Custom Elements (for example <custom-alert>)
Shadow DOM
ES Modules
the HTML <template> element
Standards have the benefit that we can rely on them to endure and work into the future in comparison to proprietary technologies in JavaScript frameworks. That’s good news for people who like to avoid the burnout-inducing churn of learning and relearning abstractions. Of course the pace of technology change with web standards tends to be slower, however that’s arguably a price worth paying for cross-platform stability and accessibility.
Some of Web Components’ historical marketing problems are now behind them, since they are supported by all major browsers and reaching maturity. Furthermore, web components have two superpowers not found in other JavaScript component approaches:
Firstly, the Shadow DOM (which is both powerful and frustrating). The Shadow DOM provides encapsulation but furthermore in progressive enhancement terms it enables the final, enhanced component output which serves as an upgrade from the baseline Light DOM HTML we provided in our custom element instance. It can be a little tricky or confusing to style, however, although there are ways.
Secondly, you can use web components standalone, i.e. natively, without any frameworks, build tools, or package managers. All that’s required to use a “standalone” is to load the <script type=module …> element for it and then use the relevant custom element HTML on your page. This gets us closer to just writing HTML rather than wrestling with tools.
Dave highlights an education gap where developers focused on HTML, CSS, and Design Systems don’t tend to use Web Components. He suggests that this is likely as a result of most web component tutorials focusing on JavaScript APIs for JavaScript developers. However we can instead frame Web Component authoring as involving a layered approach that starts with HTML, adds some CSS, then ends by applying JavaScript.
Web Components are perfectly suited to progressive enhancement. And that progressive enhancement might for example apply lots of complicated ARIA-related accessibility considerations. I really like the Tabs example where one would create a <generic-tabs> instance which starts off with simple, semantic, resilient HTML that renders headings and paragraphs…
<generic-tabs><h2>About</h2><div><p>About content goes here. Lorem ipsum dolor sit amet…</p></div><h2>Contact</h2><div><p>Contact content goes here. Lorem ipsum dolor sit amet…</p></div></generic-tabs>
…but the Web Component’s JavaScript would include a template and use this to upgrade the Light DOM markup into the final interactive tab markup…
<generic-tabs><h2slot="tab"aria-selected="true"tabindex="0"role="tab"id="generic-tab-3-0"aria-controls="generic-tab-3-0"selected="">About</h2><divrole="tabpanel"aria-labelledby="generic-tab-3-0"slot="panel"><p>About content goes here. Lorem ipsum dolor sit amet…</p></div><h2slot="tab"aria-selected="false"tabindex="-1"role="tab"id="generic-tab-3-1"aria-controls="generic-tab-3-1">Contact</h2><divrole="tabpanel"aria-labelledby="generic-tab-3-1"slot="panel"hidden><p>Contact content goes here. Lorem ipsum dolor sit amet…</p></div></generic-tabs>
Later, Dave discusses the JavaScript required to author a Custom Element. He advises that in order to avoid repeatedly writing the same lengthy, boilerplate code on each component we might use a lightweight library such as his favourite, LitElement.
Lastly, Dave argues that by creating and using web components we are working with web standards rather than building for a proprietary library. We are creating compatible components which pave the cowpaths for these becoming future HTML standards (e.g. a <tabs> element!) And why is advancing the web important? Because an easier web lowers barriers: less complexity, less tooling and setup, less gatekeeping—a web for everyone.
Here’s a “media query free” CSS one-liner which lets you set an element to have no border-radius when it is the full width of the viewport, but otherwise to have a border-radius.
It uses the same 9999 multiplication technique as Every Layout do to create a toggle.
Great for Card components which need to be full-width and non-rounded only on narrow viewports.
A new animation library, built on the Web Animations API for the smallest filesize and the fastest performance.
This JavaScript-based animation library—which can be installed via npm—leans on an existing web API to keep its file size low and uses hardware accelerated animations where possible to achieve impressively smooth results.
For fairly basic animations, this might provide an attractive alternative to the heavier Greensock. The Motion docs do however flag the limitation that it can only animate “CSS styles”. They also say “SVG styles work fine”. I hope by this they mean SVG presentation attributes rather than inline CSS on an SVG, although it’s hard to tell. However their examples look promising.
The docs website also contains some really great background information regarding animation performance.
Harry Roberts (who created ITCSS for organising CSS at scale but these days focuses on performance) has just given a presentation about the importance of getting the content, order and optimisation of the <head> element right, including lots of measurement data to back up his claims. Check out the slides: Get your Head Straight
While some of the information about asset loading best practices is not new, the stuff about ordering of head elements is pretty interesting. I’ll be keeping my eyes out for a video recording of the presentation though, as it’s tricky to piece together his line of argument from the slides alone.
However one really cool thing he’s made available is a bookmarklet for evaluating any website’s <head>:
— ct.css
I’ve been really interested in the subject of Web Performance since I read Steve Souders’ book High Performance Websites back in 2007. Although some of the principles in that book are still relevant, it’s also fair to say that a lot has changed since then so I decided to pull together some current tips. Disclaimer: This is a living document which I’ll expand over time. Also: I’m a performance enthusiast but not an expert. If I have anything wrong, please let me know.
Inlining CSS and or JavaScript
The first thing to know is that both CSS and JavaScript are (by default) render-blocking, meaning that when a browser encounters a standard .css or .js file in the HTML, it waits until that file has finished downloading before rendering anything else.
The second thing to know is that there is a “magic file size” when it comes to HTTP requests. File data is transferred in small chunks of about 14 kb. So if a file is larger than 14 kb, it requires multiple roundtrips.
If you have a lean page and minimal CSS and or JavaScript to the extent that the page in combination with the (minified) CSS/JS content would weigh 14 kb or less after minifying and gzipping, you can achieve better performance by inlining your CSS and or JavaScript into the HTML. This is because there’d be only one request, thereby allowing the browser to get everything it needs to start rendering the page from that single request. So your page is gonna be fast.
If your page including CSS/JS is over 14 kb after minifying and gzipping then you’d be better off not inlining those assets. It’d be better for performance to link to external assets and let them be cached rather than having a bloated HTML file that requires multiple roundtrips and doesn’t get the benefit of static asset caching.
Native JavaScript modules are included on a page using the following:
<scripttype="module"src="main.js"></script>
Unlike standard <script> elements, module scripts are deferred (non render-blocking) by default. Rather than placing them before the closing </body> tag I place them in the <head> so as to allow the script to be downloaded early and in parallel with the DOM being processed. That way, the JavaScript is already available as soon as the DOM is ready.
Background images
Sometimes developers implement an image as a CSS background image rather than a “content image”, either because they feel it’ll be easier to manipulate that way—a typical example being a responsive hero banner with overlaid text—or simply because it’s decorative rather than meaningful. However it’s worth being aware of how that impacts the way that image loads.
Outgoing requests for images defined in CSS rather than HTML won’t start until the browser has created the Render Tree. The browser must first download and parse the CSS then construct the CSSOM before it knows that “Element X” should be visible and has a background image specified, in order to then decide to download that image. For important images, that might feel too late.
As Harry Roberts explains it’s worth considering whether the need might be served as well or better by a content image, since by comparison that allows the browser to discover and request the image nice and early.
By moving the images to <img> elements… the browser can discover them far sooner—as they become exposed to the browser’s preload scanner—and dispatch their requests before (or in parallel to) CSSOM completion
specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance.
The benefits are most clearly seen on large and late-discovered resources. For example:
Resources that are pointed to from inside CSS, like fonts or images.
Resources that JavaScript can request such as JSON and imported scripts.
Larger images and videos.
I’ve recently used the following to assist performance of a large CSS background image:
Using third-party hosting services for fonts or other assets no longer offers the previously-touted benefit of the asset potentially already being in the user’s browser cache. Cross domain caching has been disabled in all major browsers.
You can still take advantage of the benefits of CDNs for reducing network latency, but preferably as part of your own infrastructure.
Here’s a smart and comprehensive tutorial from Andy Bell on how to create a progressively enhanced narrow-screen navigation solution using a custom element. Andy also uses Proxy for “enabled” and “open” state management, ResizeObserver on the custom element’s containing header for a Container Query like solution, and puts some serious effort into accessible focus management.
One thing I found really interesting was that Andy was able to style child elements of the custom element (as opposed to just elements which were present in the original unenhanced markup) from his global CSS. My understanding is that you can’t get styles other than inheritable properties through the Shadow Boundary so this had me scratching my head. I think the explanation is that Andy is not attaching the elements he creates in JavaScript to the Shadow DOM but rather rewriting and re-rendering the element’s innerHTML. This is an interesting approach and solution for getting around web component styling issues. I see elsewhere online that the innerHTML based approach is frowned upon however Andy doesn’t “throw out” the original markup but instead augments it.
Astro looks very interesting. It’s in part a static site builder (a bit like Eleventy) but it also comes with a modern (revolutionary?) developer experience which lets you author components as web components or in a JS framework of your choice but then renders those to static HTML for optimal performance. Oh, and as far as I can tell theres no build pipeline!
Astro lets you use any framework you want (or none at all). And if most sites only have islands of interactivity, shouldn’t our tools optimize for that?
People have been posting some great thoughts and insights on Astro already, for example:
I’ve been on the lookout for a lightweight, web standards based slide deck solution for a while and this one from Lea Verou could well be perfect.
It has keyboard navigation, video and code demo support, an index page and much more… and it’s all powered by straightforward HTML, CSS and JavaScript. I need to give this a spin!
Max’s demo is really clever and features lots of interesting web component related techniques.
I came up with this demo of a book store. Each of the books is draggable and can be moved to one of three sections, with varying available space. Depending on where it is placed, different styles will be applied to the book.
Some of the techniques I found interesting included:
starting with basic HTML for each book and its image, title, and author elements rather than an empty custom element, thereby providing a resilient baseline
wrapping each book in a custom book-element tag (which the browser would simply treat like a div in the worst case scenario)
applying the slot attribute to each of the nested elements, for example slot="title"
including a template with id="book-element" at the top of the HTML. This centralises the optimal book markup, which makes for quicker, easier, and less disruptive maintenance. (A template is parsed but not rendered by the browser. It is available solely to be referenced and used by JavaScript)
including slots within the template, such as <slot name="title">
putting a style block within the template. These styles target the book component only, and include container query driven responsiveness
targetting the <book-element> wrapper element in CSS via the :host selector, and applying contain to set it as a container query context
targetting a slot in the component CSS using (for example) ::slotted(img)
Thoughts
Firstly, in the basic HTML/CSS, I might ensure images are display: block and use div rather than span for a better baseline appearance should JavaScript fail.
Secondly, even though this tutorial is really nice, I still find myself asking: why use a Web Component to render a book rather than a server-side solution when the latter removes the JS dependency? Part of the reason is no doubt developer convenience—people want to build component libraries in JavaScript if that’s their language of choice. Also, it requires less backend set-up and leads to a more portable stack. And back-end tools for component-based architectures are generally less mature and feature-rich then those for the front-end.
One Web Component specific benefit is that Shadow DOM provides an encapsulation mechanism to style, script, and HTML markup. This encapsulation provides private scope that both prevents the content of the component from being affected by the external document, and keeps its CSS and JS from leaking out… which might be nice for avoiding the namespacing you’d otherwise have to do.
I have a feeling that Web Components might make sense for some components but be neither appropriate nor required for others. Therefore just because you use Web Components doesn’t mean that you suddenly need to feel the need to write or refactor every component that way. It’s worth bearing in mind that client-side JavaScript based functionality comes with a performance cost—the user needs to wait for it to download. So I feel there might be a need to exercise some restraint. I want to think about this a little more.
I love hearing about clever front-end solutions which combine technologies and achieve multiple goals. In Zach’s post we hear how Netlify’s website suffered from layout shift when conditionally rendering dismissible promo banners, and how he addressed this by rethinking the problem and shifting responsibilities around the stack.
Here’s my summary of the smart ideas covered in the post:
decide on the appropriate server-rendered content… in this case showing rather than hiding the banner, making the most common use case faster to load
have the banner “dismiss” button’s event handling script store the banner’s href in the user’s localStorage as an identifier accessible on return visits
process lightweight but critical JavaScript logic early in the <head>… in this case a check for this banner’s identifier existing in localStorage
under certain conditions – in this case when the banner was previously seen and dismissed – set a “state” class (banner--hide) on the <html> element, leading to the component being hidden seamlessly by CSS
build the banner as a web component, the first layer of which being a custom element <announcement-banner> and the second a JavaScript class to enhance it
delegate responsibility for presenting the banner’s “dismiss” button to the same script responsible for the component’s enhancements, meaning that a broken button won’t be presented if that script were to break.
So much to like in there!
Here are some further thoughts the article provoked.
Web components FTW
It feels like creating a component such as this one as a web component leads to a real convergence of benefits:
tool-free, async loading of the component JS as an ES module
fast, native element discovery (no need for a document.querySelector)
enforces using a nice, idiomatic class providing encapsulation and high-performing native callbacks
resilience and progressive enhancement by putting all your JS-dependent stuff into the JS class and having that enhance your basic custom element. If that JS breaks, you still have the basic element and won’t present any broken elements.
Even better, you end up with framework-independent, standards-based component that you could share with others for reuse elsewhere, just like Zach did.
Multiple banners
I could see there being a case where there are multiple banners during the same time period. I guess in that situation the localStorage banner value could be a stringified object rather than a simple, single-URL string.
Setting context on the root
It’s really handy to have a way to exert just-in-time control over the display of a server-rendered element in a way that avoids flashes of content… and adding a class to the <html> element offers that. In this approach, we run the small amount of JavaScript required to test a local condition (e.g. checking for a value in localStorage) really early. That lets us process our conditional logic before the element is rendered… although this also means that it’s not yet available in the DOM for direct manipulation. But adding a class to the HTML element means that we can pre-prepare CSS to use that class as a contextual selector for hiding the element.
We’re already familiar with the technique of placing classes on the root element from libraries like modernizr and some font-loading approaches, but this article serves as a reminder that we can employ it whenever we need it.
Handling the close button
Zach’s approach to handling the banner’s dismiss button was interesting. He makes sure that it’s not shown unless the web component’s JavaScript runs successfully which is great, but rather than inject it with JavaScript he includes it in the initial HTML but hidden with CSS, and his method of hiding is opacity.
We use opacity to toggle the close button so that it doesn’t reflow the component when it’s enabled via JavaScript.
I love that level of diligence! Typically I prefer to delegate responsibility for inserting JS-dependent buttons to JavaScript because in comparison to including a button in the server-rendered HTML then hiding it, it feels more resilient and a more maintainable separation of concerns. However as always the best solution depends on the situation.
If I were going down Zach’s route I think I’d replace opacity with visibility since the latter hiding method removes the hidden element from the document which feels more accessible, while still avoiding triggering the reflow that display would.
Side-thoughts
In a server-side scripted application – one using Rails or PHP, for example – you could alternatively handle persisting state with cookies rather than localStorage… allowing you to test for the presence of the cookie on the server then handle conditional rendering of the banner on the server too, rather than needing classes which trigger hiding. I can see an argument for that. Thing is though, not everyone’s working in that environment. Zach has provided a standalone solution.
I’ve played with the various HTML5 Observer APIs (IntersectionObserver, ResizeObserver and MutationObserver) a little over the last few years—for example using ResizeObserver in a container query solution for responsive grids. But in all honesty their roles, abilities and differences haven’t yet fully stuck in my brain. So I’ve put together a brief explainer for future reference.
Intersection Observer
Lets you watch for when an element of your choice intersects with a root element of your choice—typically the viewport—and then take action in response.
So you might watch for a div that’s way down the page entering the viewport as a result of the user scrolling, then act upon that by applying a class which animates that div’s opacity from 0 to 1 to make it fade in.
Here’s how it works:
Instantiate a new IntersectionObserver object, passing in firstly a callback function and secondly an options array which specifies your root element (usually the viewport, or a specific subsection of it).
Call observe on your instance, passing in the element you want to watch. If you have multiple elements to watch, you could call observe repeatedly in a loop through the relevant NodeList.
in the callback function add the stuff you want to happen in response to “intersecting” and “no longer intersecting” events.
Mutation Observer
Lets you watch for changes to the attributes or content of DOM elements then take action in response.
You might use this if you have code that you want to run if and when an element changes because of another script.
Here’s how it works:
Your typical starting point is that you already have one or more event listeners which modify the DOM in response to an event.
Instantiate a new MutationObserver object, passing in a callback function.
The callback function will be called every time the DOM is changed.
Call observe on your instance, passing in as first argument the element to watch and as second argument a config object specifying what type of changes you’re interested in, for example you might only care about changes to specific attributes.
your callback function provides an array of MutationRecord objects—one for each change that has just taken place—which you can loop through and act upon.
Resize Observer
Lets you watch for an element meeting a given size threshold then take action in response.
For example you might add a class of wide to a given container only when it is wider than 60em so that new styles are applied. This is a way of providing container query capability while we wait for that to land in CSS.
Or you might load additional, heavier-weight media in response to a certain width threshold because you feel you can assume a device type that indicates the user is on wifi. Adding functionality rather than applying styles is something we could not achieve with CSS alone.
Given that Container Query support is coming in CSS and that we can usually get by without it in the meantime, I don’t think it’s something I need so desperately that I’ll keep reaching for JavaScript to achieve it. However that’s not the only use for ResizeObserver.
It’s also worth remembering that it’s not all about width: ResizeObserver can also be used to detect and respond to changes to an element’s height. An example might be watching for changes to a chat window’s height—something that’s liable to happen as new messages appear—and then ensuring the focus stays at the bottom, on the latest message.
References
Steve Griffiths has some great video tutorials on these topics.
On my personal website I currently use three web fonts from the Source Sans 3 group: regular, italic and semibold. I self-host my fonts because that’s a good practice. Additionally I use a variety of special characters to add some typographic life to the text.
When self-hosting it’s important from a performance perspective to minimise the weight of the font files your visitors must download. To achieve this I subset my fonts so as to include only the characters my pages use but no more. Here’s how I do it.
Note: to follow these steps, you’ll need to install glyphhanger. The Github page includes installation and usage guidelines however there are a few common installation pitfalls so if you’re on a Mac and run into trouble I recommend checking Sara Soueidan’s How I set up Glyphhanger on macOS to get you back on track.
For the purposes of this walkthrough I’ll assume you have a directory in your application named fonts.
Start by deleting any existing custom font files from your application’s fonts directory.
Run your site locally in an incognito browser window. For my Eleventy-based site, I run npm run serve which serves the site at http://localhost:8080.
Visually check your locally-running site to ensure that now you’ve deleted your web fonts it’s no longer serving them and is instead rendering text using system fonts.
Visit the source page for your custom fonts—in my case the Github repository for Source Sans 3. Download in .ttf format the latest versions of the fonts you need and place them in your fonts directory. For me these are:
Regular,
Italic; and
Semibold.
You’ll notice the large file sizes of these .ttf files. For example Source Sans 3’s Regular.ttf font is 299 kb.
At the command line, cd into your fonts directory.
Now we’re going to run glyphhanger on one font at a time. This fantastic tool will intelligenty crawl your website to check which glyphs are currently in use for the specified weight then include those in a subset file which it outputs in .ttf, .woff and .woff2 formats. I use glyphhanger’s spider option so that it spiders multiple pages (rather than just one) at a time, meaning that it is more likely to catch all the special characters I’m using.
U+20-23,U+25-2A,U+2C-5B,U+5D,U+5F,U+61-7D,U+A9,U+B7,U+BB,U+D7,U+E9,U+F6,U+200B,U+200E,U+2013,U+2014,U+2018,U+2019,U+201C,U+201D,U+2026,U+2122,U+2190,U+2192,U+2615,U+FE0F
Subsetting SourceSans3-Regular.ttf to SourceSans3-Regular-subset.ttf (was 292.24 KB, now 46.99 KB)
Subsetting SourceSans3-Regular.ttf to SourceSans3-Regular-subset.zopfli.woff (was 292.24 KB, now 22.14 KB)
Subsetting SourceSans3-Regular.ttf to SourceSans3-Regular-subset.woff2 (was 292.24 KB, now 17.77 KB)
The .woff2 subset file has reduced the file size from 299 kb to 17.77 kb which is pretty impressive!
Update your CSS to point at the new woff2 and woff subset files for your font. My updated CSS looks like this:
@font-face{font-family: Source Sans Pro;src:url(/fonts/sans/SourceSans3-Regular-subset.woff2)format("woff2"),url(/fonts/sans/SourceSans3-Regular-subset.zopfli.woff)format("woff");font-weight: 400;font-display: swap;}
Check your locally running application to ensure that the relevant text (body copy in this case) is now being served using the web font rather than fallback font, and that special characters are also being served using the web font.
I’ll usually crack open the Fonts panel in Firefox’s DevTools and check that, amongst other things, my pagination links which use the rightward pointing arrow character (→ or unicode U+2192) are rendering it using Source Sans Pro and not sticking out like a sore thumb by using Helvetica due to the glyph not being present in the subset.
Delete the .ttf file you started with and any .ttf subsets generated, because you won’t serve files in that format to your website visitors.
Repeat the glyphhanger subsetting and CSS updating process for any other weights (italic, semibold) or custom fonts you want to subset.
One last handy tip: if there’s a weight for which I don’t need a fancy character set (for example the Semibold I use for headings), I might just grab default latin charset woff and woff2 files from the Google Webfonts Helper. The files tend to be small and well-optimised and this can save a little time. (This is only possible if the font is available from Google Fonts which is true in the case of Source Sans 3.)
The Great Divide between so-called front-end developers is real! Here, Brad Frost proposes some modern role definitions.
A front-of-the-front-end developer is a web developer who specializes in writing HTML, CSS, and presentational JavaScript code.
A back-of-the-front-end developer is a web developer who specializes in writing JavaScript code necessary to make a web application function properly.
Brad also offers:
A succinct way I’ve framed the split is that a front-of-the-front-end developer determines the look and feel of a button, while a back-of-the-front-end developer determines what happens when that button is clicked.
I’m not sure I completely agree with his definitions—I see a bit more nuance in it. Then again, maybe I’m biased by my own career experience. I’m sort-of a FOTFE developer, but one who has also always done both BOTFE and “actual” back-end work (building Laravel applications, or working in Ruby on Rails etc).
I like the fact that we are having this discussion, though. The expectations on developers are too great and employers and other tech people need to realise that.
A couple of interesting points I took from Chris’s article:
this simple new means of declaring aspect-ratio should soon hopefully supersede all the previous DIY techniques;
if you apply a CSS aspect-ratio to an element which has no explicit width set, we still get the effect because the element’s auto (rendered) width is used, then by combining that with the CSS aspect-ratio the browser can calculate the required height, then apply that height;
if the content would break out of the target aspect-ratio box, then the element will expand to accommodate the content (which is nice). If you ever need to override this you can by applying min-height: 0;
if the element has either a height or a width set, the other of the two is calculated from the aspect ratio;
if the element has both a height and width set, aspect-ratio is ignored.
Regarding browser support: at the time of writing aspect-ratio is supported in Chrome and Edge (but not IE), is coming in Firefox and Safari, but as yet there’s no word regarding mobile. So I’d want to use it as a progressive enhancement rather than for something mission critical.
Here’s Andy Bell recommending using CSS clamp() to control your wrapper/container width because it supports setting a preferred value in vw to ensure sensible gutters combined with a maximum tolerance in rem—all in a single line of code.
If we use clamp() to use a viewport unit as the ideal and use what we would previously use as the max-width as the clamp’s maximum value, we get a much more flexible setup.
This is pretty cool because I know from experience that coding responsive solutions for wrappers can be tricky and you can end up with a complex arrangement of max-width and media queries whilst still—as Andy highlights—not providing optimal readability for medium-sized viewports.
Using CSS Grid with minmax() is one possible approach to controlling wrappers however this article offers another (potentially better) tool for your kit.
It’s worth noting that Andy could probably have just used width: min(90vw, 70rem) here (as Christopher suggested) because setting the lower bound provided by clamp() is only necessary if your element is likely to shrink unexpectedly and a regular block-level element wouldn’t do that. The clamp approach might be handy for flex items, though.
Need to overlay one HTML element on top of and fully covering another, such as a heading with translucent background on top of an image? Michelle Barker has us covered with this blog post in which she creates an overlay utility to handle this. She firstly shows how it can be accomplished with positioning, then modernises her code using the inset CSS logical property, before finally demonstrating a neat CSS Grid based approach.
I like this and can see myself using it – especially the Grid-based version because these days I try to avoid absolute positioning and use modern layout tools instead where possible.
I’ve mocked up a modified version on Codepen, sticking with CSS Grid for simplicity. I was going to also wrap it in an @supports (display:grid) however the styles are all grid-based so in the case of no grid support they simply wouldn’t run, rather than causing any problems.
A fantastic so-called “Scroll Story” from Robin Rendle. In his own words it’s “an elaborate blog post where I rant about a thing” however given the beautiful typography, layout and illustrations on show I think he’s selling it a little short!
The content of this “story” is pretty interesting – Robin laments the fact that web authors often need newsletters, or to “spam social media” in order to publicise articles on their websites, because most people don’t use RSS (awareness is too low and barriers to entry too great).
However it’s the story’s design and technical implementation which really caught my eye.
Robin does some really cool stuff with the CSS scroll-snap-type property and also explains some steps he had to take to tame differing implementations of height:100vh across browsers.
Here’s a lovely intrinsically responsive (no media queries) photo gallery solution from Stephanie Eckles. It can accommodate differently sized images and achieves its layout by a combination of flexbox features (flex-wrap, flex-basis) and by applying object-fit: cover to photos to make them fully cover their parent list items.
In web development it’s useful when we can say “if the browser supports X, then we know it also supports Y”.
There was a small lightbulb moment at work earlier this year when we worked out that:
if the user’s browser supports CSS Grid, then you know you it also supports custom properties.
Knowing this means that if you wrap some CSS in an @supports(display:grid) then you can also safely use custom properties within that block.
I love this rule of thumb! It saves you looking up caniuse.com for each feature and comparing the browser support.
This weekend I did some unplanned rabbit-holing on the current state of (and best practices for using) ES modules in the browser, as-is and untranspiled. That revealed another interesting rule of thumb:
any browser that supports <script type="module"> also supports let and const, async/await, the spread operator, etc.
One implication of this is that if you currently build a large JavaScript bundle (due to being transpiled down to ES 3/5 and including lots of polyfills) and ship this to all browsers including the modern ones… you could instead improve performance for the majority of your visitors by configuring your bundler to generate two bundles from your code then doing:
// only one of these will be used.
<scripttype="module"src="lean-and-modern.js"></script><scriptnomodulesrc="bulky-alternative-for-old-browsers.js"></script>
I might make a little page or microsite for these rules of thumb. They’re pretty handy!
Even though more and more people get access to the internet every day, not all of them have fast gigabit connections or unlimited data. Using the media query prefers-reduced-data we can keep our sites accessible to everyone.
I’ve long wondered if there could be a way to tailor content to a user based on the speed of their internet connection, especially when considering features like responsive images. This looks like it might be the way to do that (although browser support is currently non-existent). It also allows us to respect the user’s wishes on how much data / battery life etc they’re willing to spare for your website.
We have new properties in CSS for styling underlines, as explained here by Jen Simmons.
The relevant properties are:
text-decoration-thickness
text-decoration-color
text-underline-offset
text-decoration-skip-ink
The skip-ink concept becomes more interesting (to me at least) when you're also using the other properties (especially offset) in order to start the underline higher up the word causing it to appear behind it.
Scott Jehl’s experimental take on a container/element query aimed at letting us set responsive styles for our elements based on their immediate context rather than that of the viewport.
I made a quick and minimal take on approximating Container/Element Queries using a web component and basic CSS selectors.
The idea is that for any given instance of the <c-q> custom element / web component you would define a scoped custom property which sets the pixel min-widths you’re interested in, like so:
Zero to many of those numeric min-width values will appear in the element’s data-min-width HTML attribute based on which (if any) of them the element’s width is equal to or greater than.
You can style the element based on their presence using the ~= attribute selector, like this:
This is why, over years of building for the web, I have learned that I can significantly cut down on the entropy my future self will have to face by authoring web projects in vanilla HTML, CSS, and JS. I like to ask myself questions like:
Could this be done with native ES modules instead of using a bundler?
Could I do this with DOM scripting instead of using a JS framework?
Could I author this in CSS instead of choosing a preprocessor?
Fantastic post from Jim Neilson about how your future self will thank you if you keep your technology stack simple now.
In order to code modern component designs we often need to hide then reveal elements. At other times we want to provide content to one type of user but hide it from another because it’s not relevant to their mode of browsing. In all cases accessibility should be front and centre in our thoughts. Here’s my approach, heavily inspired by Scott O’Hara’s definitive guide Inclusively Hidden.
Firstly, avoid the need to hide stuff. With a bit more thought and by using existing fit-for-purpose HTML tools, we can perhaps create a single user interface and experience that works for all. That approach not only feels like a more equal experience for everyone but also removes margin for error and code maintenance overhead.
With that said, hiding is sometimes necessary and here are the most common categories:
Hide from everyone
Hide visually (i.e. from sighted people)
Hide from Assistive Technologies (such as screen readers)
Hide from everyone
We usually hide an element from everyone because the hidden element forms part of a component’s interface design. Typical examples are tab panels, off-screen navigation, and modal dialogues that are initially hidden until an event occurs which should bring them into view. Initially these elements should be inaccessible to everyone but after the trigger event, they become accessible to everyone.
Implementation involves using JavaScript to toggle an HTML attribute or class on the relevant element.
For basic, non-animated show-and-hide interactions you can either:
toggle a class which applies display: none in CSS; or
toggle the boolean hidden attribute, which has the same effect but is native to HTML5.
Both options work well but for me using the hidden attribute feels a little simpler and more purposeful. My approach is to ensure resilience by making the content available in the first instance in case JavaScript should fail. Then, per Inclusive Components’ Tabs example, JavaScript applies both the “first hide” and all subsequent toggling.
Here’s some CSS that supports both methods. (The hidden attribute doesn’t strictly need this but it’s handy to regard both options as high-specifity, “trump-everything-else” overrides.)
For cases where you are animating or sliding the hidden content into view, toggle the application of CSS visibility: hidden because this also removes the element from the accessibility tree but unlike display, can be animated. Note that with visibility: hidden the physical space occupied by the element is still retained, therefore it’s best to pair it with position: absolute or max-height: 0px; overflow: hidden to prevent that “empty space while hidden” effect. For example:
We’ll usually want to hide something visually (only) when its purpose is solely to provide extra context to Assistive Technologies. An example would be appending additional, visually-hidden text to a “Read more” link such as “about Joe Biden” since that would be beneficial to screen reader users.
We can achieve this with a visually-hidden class in CSS and by applying that class to our element.
Essentially this hides whatever it’s applied to unless it’s a focusable element currently being focused by screen reader controls or the tab key, in which case it is revealed.
Note that if adding to link text to make it more accessible, always append rather than inserting words into the middle of the existing text. That way, you avoid solving an accessibility for one group but creating another for another group (Dragon speech recognition software users).
Visually hidden until focused
There are other CSS approaches to hiding visually. One approach is to not only add position: absolute (removing the element from the document flow) but also position it off-screen with left: -100vw or similar. The use case for this approach might be when you want your visually hidden element to support being revealed and for that reveal to occur via a transition/animation from off-screen into the viewport. See Scott O’Hara’s off screen skip-links example.
Hide from Assistive Technologies (such as screen readers)
We sometimes hide visual elements from Assistive Technologies because they are decorative and have accompanying text, for example a “warning” icon with the text “warning” alongside. If we did not intervene then Assistive Technologies would read out “warning” twice which is redundant.
To achieve this we can apply aria-hidden="true" to our element so that screen readers know to ignore it. In the following examples we hide the SVG icons within buttons and links, safe in the knowledge that the included “Search” text is providing each interactive element with its accessible name.
Rachel Andrew explains how to write CSS for a nicely optimised printed page that uses a minimum of ink and paper and ensures that content is easy to read.
I really like the section on Workflow that compares the options of
organising your print styles as a separate stylesheet loaded via a <link> in the <head> (this is the “traditional” approach); versus
using @media print {} in your main styles, which opens up the opportunity to locate each component’s print styles beside its main styles.
As Rachel notes, the first option might feel tidy (and keeping print styles separate reduces the size of your main stylesheet) however on larger sites this approach can lead to print styles being “out of sight, out of mind” and poorly maintained.
I think there will always be a need for 80% global print styles, supplemented by a sprinkling of component-specific print styles (and maybe even the odd utility class). It’s just a case of how you organise this.
I had an idea that you could maybe put the global print styles in a separate sheet and locate the component styles beside components in the main stylesheet however because we tend to want global print styles to add to and override main styles you’d want the print_globals file coming after the main styles, but that then screws up the order of the component-specific print styles. When @layers with <link> is supported perhaps this could all work! Until then, the future of print CSS for large design systems is perhaps Option 2: colocate print styles with screen styles.
Sometimes you want to create a line break after an inline element, while retaining that inline element’s inline status.
A lovely trick from Andy Bell for breaking after an inline element (such as a form label) using a pseudo-element and the white-space property, so that we can avoid setting the element to display: block (thereby becoming full-width etc) when we don’t want that.
Daniel Post shared a really cool performance-optimisation trick for Eleventy on Twitter the other day. When statically generating your site you can loop through your pages and, for each, use PurgeCSS to find the required CSS, then inline that into the <head>. This way, each page contains only the CSS it needs and no more!
I’ve just installed this on my personal site. I was already inlining my CSS into the <head> but the promise of only including the minimum CSS that each specific page needs was too good to resist.
Turned out it was a breeze to get working, a nice introduction to Eleventy transforms, and so far it’s working great!
In general this is a decent article on non-JavaScript-based mobile navigation options, but what I found most interesting is the idea of having a separate page for your navigation menu (at the URL /menu, for example).
Who said navigation has to be in the header of every page? If your front end is extremely lightweight or if you have a long list of menu items to display in your navigation, the most practical method might be to create a separate page to list them all.
I also noted that the article describes a method where you can “spoof” a slide-in hamburger menu without JS by using the checkbox hack. I once coded a similar “HTML and CSS -only” hamburger menu, but opted instead to use the :target pseudo-class in combination with the adjacent sibling selector, as described by Chris Coyier back in 2012.
Scott Jehl of Filament Group demonstrates a one-liner technique for loading external CSS files without them delaying page rendering.
While this isn’t really necessary in situations where your (minified and compressed) CSS is small, say 14k or below, it could be useful when working with large CSS files and want to deliver critical CSS separately and the rest asynchronously.
Today, armed with a little knowledge of how the browser handles various link element attributes, we can achieve the effect of loading CSS asynchronously with a short line of HTML. Here it is, the simplest way to load a stylesheet asynchronously:
Max shows us how to build a colour theme switcher to let users customise your website. He uses a combination of Eleventy, JSON, Nunjucks with macros, a data attribute on the html element, CSS custom properties and a JavaScript based switcher.
Given what we can now do with CSS, do we still need Sass?
Sass was the hare. CSS is the tortoise. Sass blazed the trail, but now native CSS can achieve much the same result.
Jeremy’s post starts by talking about the new CSS clamp function and how it can be used for scalable type, then veers into a question of whether we still need Sass or if modern CSS now covers our needs.
This is really interesting and definitely gives me pause to consider whether I can simplify my development stack by removing a tool.
However I guess one reason (not mentioned in Jeremy’s post) you might want Sass is that many of the CSS functions which provide similar effects to mixins, variables etc are currently only supported in the most modern, standards-compliant browsers. Sass can pre-process its variables and mixins into older, more broadly-supported CSS. So choosing the pure CSS, processor-free option within a progressive enhancement oriented approach might mean that your broadly-supported baseline is more basic than it would be by using Sass. That’s the sort of decision I could take fairly lightly for my personal website, but I could see it being less palatable for stakeholders working on larger sites.
For example, if your site needs to support IE11 and theming which includes custom colour schemes, unfortunately you don’t have the luxury of putting all your eggs in the native CSS custom properties basket.
We’re not going to try to replicate everything that the browser does by default with a native select element. We’re going to literally use a select element when any assistive tech is used. But when a mouse is being used, we’ll show the styled version and make it function as a select element.
This custom-styled select solution satisfies those who insist on a custom component but retains all the built-in accessibility we get from native form controls. I also really like the use of a @media (hover: hover) media query to detect an environment with hover (such as a computer with a mouse rather than a mobile browser on a handheld device).
Stephanie Eckles with a beautifully presented series of articles on how to use modern CSS to tackle some of the enduring challenges of web development including dropdown navigation, centring and styling buttons.
A handy tool that generates the required HTML and CSS for various section separator effects (including diagonal lines, spikes, and waves) by cleverly manipulating backgrounds and generated content.
Documentation for the BEM component and CSS class-naming notation
methodology BEM was invented at Yandex to develop sites which should be launched fast and supported for a long time. It helps to create extendable and reusable interface components.
Here’s Chris Ferdinandi with a list of resources to help those who are new to web development get started. I’m keeping this one handy so I can share it with any friends who’re thinking of getting into this game.
Check whether or not a CSS property is a good candidate for smooth animation based on whether updates to its value trigger expensive changes (to, for example, “element geometry”) causing layout updates and repaints.
width and height are both poor candidates whereas transform is good.
Let’s create a pure CSS effect that changes the color of a text link on hover – but slide that new color in instead of simply swapping colors.
Katherines post explores four different techniques to achieve the effect, and their comparative pros and cons with regard to accessibility, performance, and browser support.
Technique 4, which uses a CSS transform seems to be the most flexible, best-performing and has best cross-browser support, however because it requires adding a semantically redundant <span> into the anchor I would use it sparingly rather than on all links by default.
Removing underlines from links in HTML text presents an accessibility challenge. In order for a design to be considered accessible, there is now a three-sided design contraint - or what I call "The Contrast Triangle". Your text, links and background colors must now all have sufficient contrast from each other. Links must have a contrast ratio of 3:1 from their surrounding text. By not using underlines, a design has to rely on contrast alone to achieve this.
It’s interesting that Chip says that this level of contrast is needed “when we don’t use underlines on links”.
By not using underlines, a design has to rely on contrast alone to achieve this.
So this seems to be yet another good reason to include underlines in links, i.e. if you underline your links then you don’t need to worry quite as much about a third level of contrast.
Indeed, when you toggle on the “Show underlines” option on this tool, it then removes the requirement to ensure additional contrast between hyperlinks and standard body text.
However, even if your links in flowing prose are underlined, there’s always likely to be places (Navigation, Footer, CTAs etc) where you’ve probably disabled underlines on links for design effect, so I reckon this is useful for most websites.
The BBC Global Experience Language (GEL) Technical Guides are a series of framework-agnostic, code-centric recommendations and examples for building GEL design patterns in websites. They illustrate how to create websites that comply with all BBC guidelines and industry best practice, giving special emphasis to accessibility.
Heydon Pickering (author of Inclusive Components and co-creator of Every Layout) has implemented and documented over 25 of the BBC's design patterns. These are sure to be loaded with best practices and clever tricks for making resilient, accessible modern UI components. (via @heydonworks)
A nice list of tips and tools on how to use simpler browser standards and APIs to avoid the added weight of unnecessary JavaScript and libraries.
Lodash, Moment and other similar libraries are expensive and we don’t always need them. This Github repo contains a host of nice tips, snippets and code–analysing tools.
One cautionary note regarding the idea of replacing JS with CSS: although the idea of using CSS rather than JavaScript for components like tabs and modals seems nice at first, it doesn’t properly consider that we often need JS for reasons of accessibility, in order to apply the correct aria attributes when the state of a UI component is modified.
Via Will Matthewson at work (FreeAgent) during our group conversation on JavaScript strategy.
I first got into web design/development in the late 90s, and only as I type this sentence do I realize how long ago that was. Here’s a history of CSS and web design, as I remember it.
A fantastic and amusing account of how we progressed from no CSS (the early days of font tags, inline styles and tables for layout), through bad browsers, untold hacks and browser prefixes, to the relative luxury of today’s tools such as Flexbox and CSS Grid.
I wanted to see if it was possible to create SVG charts that would work without JS. Well, it is. I've also created an experimental Svelte component library called Pancake to make these techniques easier to use.
A lovely modern, progressively-enhanced approach to data visualisation that uses primarily SVG, HTML and CSS but can be enhanced with JavaScript for Node-based generation or client-side interactivity, if required. (via @jamesmockett)
Here’s Rob Weychert advocating a combination of CSS custom properties, calc() and Sass to automate the construction of a flexible typographic scale in CSS.
Subgrid for CSS Grid Layout has arrived in Firefox and it looks great. Here’s how I wrapped my head around the new concepts.
While MDN has some nice examples, I generally find I need a little extra time, trial and error and note-making in order to fully grasp CSS Grid concepts.
For example, I always need to remind myself that parts of the syntax – such as grid-template-columns selectors – refer to grid lines rather than columns.
So I created a Subgrid example pen with guideline notes for future reference. Note: make sure to open the pen in Firefox rather than any other browser, because at the time of writing only Firefox supports Subgrid!
Thanks to a great tip from Lucas Hugdahl on Twitter, here’s how to use CSS custom properties (variables) in your transforms so you don't need to rewrite the whole transform rule in order to transition (animate) a single property.
Let’s take the simple example of a button that we want to increase in size when hovered.
By using a custom property for the scale value, we can keep things DRYer in our :hover rule by only updating that variable rather than rewriting the entire transform rule.
Create a more flexible component which allows the text to wrap based on the content rather than the viewport size.
Here, Mandy Michael explores similar territory to Every Layout in suggesting that not all responsive pattern challenges require, or indeed are best served by, media queries.
The example here is a pipe-separated text pair (I could imagine an author and publish date meta line) which Mandy wants to wrap (with pipe separator hidden) only when the content and container require it, rather than based on the less-relevant viewport width.
She uses a clever combination of flex-wrap:wrap, generated content, padding, transform and overflow-y:hidden to achieve her goal.
Every now and then something comes along in the world of web design that represents a substantial shift. The launch of Every Layout, a new project from Heydon Pickering and Andy Bell, feels like one such moment.
In simple terms, we get a bunch of responsive layout utilities: a Box, a Stack, a Sidebar layout and so on. However Every Layout offers so much more—in fact for me it has provided whole new ways of thinking and talking about modern web development. In that sense I’m starting to regard it in terms of classic, game-changing books like Responsive Web Design and Mobile First.
Every Layout’s components, or primitives, are self-governing and free from media queries. This is a great step forward because media queries tie layout changes to the viewport, and that’s suboptimal when our goal is to create modular components for Design Systems which should adapt to variously-sized containers. Every Layout describe their components as existing in a quantum state: simultaneously offering both narrow and wide configurations. Importantly, the way their layouts adapt is also linked to the dynamic available space in the container and the intrinsic width of its contents, which leads to more fluid, organic responsiveness.
Every Layout’s approach feels perfect for the new era of CSS layout where we have CSS Grid and Flexbox at our disposal. They use these tools to suggest rather than dictate, letting the browser make appropriate choices based on its native algorithms.
When it comes to webfonts, if you want to serve an accessible and high performance experience across device types it’s not as straightforward as just specifying your fonts in CSS then hoping for the best.
We likely have goals such as the following:
avoid Flash of Invisible Text (FOIT). Flash of Unstyled Text (FOUT) is preferable.
provide a good experience for users on slow connections.
while favouring FOUT over FOIT, take care to minimise jarring reflows.
Browser support is also a factor. For example font-display: swap seems like a great option however as Chris Ferdinandi pointed out in Why use the vanilla JS fontfaceset.load method instead of CSS font-display: swap it doesn’t have comprehensive mobile support. Since mobile users are regularly on slower connections they are likely to be hit hard by load times incurred due to custom fonts, therefore a solution which doesn’t cater to them is less attractive.
I tend to go for FOUT with a class—an approach that is reliable and good enough for most use cases. The idea is to use JavaScript to detect when a font has loaded successfully, and only then add a fonts-loaded class to the HTML element causing CSS scoped to that class to take effect. To date I’ve handled the detection using Bram Stein’s Font Face Observer to benefit from greater browser support (it handles IE) than I’d get using the native FontFaceSet.load() however I expect to gravitate toward the native API solution soon.
I’ve also experimented with pre-loading fonts in the <head> in combination with font-display: swap on this, my personal website. This was inspired by the font-loading approach Zach Leatherman took with CSS-Tricks. However due to the fonts I’m using right now I’d currently be preloading too heavy a load for slow connections (thus temporarily blocking initial page render) so I’d need to go further and introduce two-stage loading into that mix.
I’ve also found that your choice of font and font host can really influence (constrain) the flexibility and options you have for font features and loading.
font-display: swap can only be applied on a self-hosted font or one hosted on Google Fonts (via a special querystring parameter on the font URL). So this CSS-only approach is not available with (for example) fonts hosted on Adobe Fonts or fonts.com.
link rel=preload is only available for self-hosted fonts because you need to be able to rely on the URL not changing, and you can’t rely on that for externally hosted fonts.
You might want to use the opentype features of a font but are they available in your font hosting/loading solution? Some of the fonts hosted on Google Fonts have nice OpenType features but by default these features are pruned out.
Getting access to the source .ttf file is beneficial as it allows you to subset the font, including special features and characters but also cutting out any your website does not require. Google Fonts have an open license which means we don’t need to lean on their hosting but can instead download fonts in .ttf, subset them (I use Glyphhanger) and self-host them.
This is all a work in progress and I’m still working this stuff out.
Cassie Evans shows us how to combine background–size, a linear-gradient based background-image and a keyframe animation (all in HTML and CSS) for a lovely progressive underline effect on multi-line text.
Here’s the gist of it:
<h2>This is a multi-line spanning animated underline. This took an annoyingly long time to figure out.</h2>
For a while now I’ve been using gulp-autoprefixer as part of my front-end build system. However, I’ve just removed it from my boilerplate. Here’s why.
The npm module gulp-autoprefixer takes your standard CSS then automatically parses the rules and generates any necessary vendor-prefixed versions, such as ::-webkit-input-placeholder to patch support for ::placeholder in older Webkit browsers.
I’ve often felt it excessive—like using a hammer to crack a nut. And I’ve wondered if it might be doing more harm than good, by leading me to believe I have a magical sticking plaster for non-supporting browsers when actually (especially in the case of IE) the specific way in which a browser lacks support might be more nuanced. Furthermore I’ve never liked the noise generated by all those extra rules in my CSS output, especially when using the inspector to debug what would otherwise be just a few lines of CSS.
But I always felt it was a necessary evil.
However, I’ve just removed gulp-autoprefixer from my boilerplate. Why? Because:
Browsers are no longer shipping any new CSS with prefixes, and as at 2019, they haven’t been for years;
With the browsers that do require prefixed CSS now old and in the minority, it feels like progressive enhancement rather than “kitchen sink” autoprefixing should take care of them. (Those browsers might not get the enhanced experience but what they’ll get will be fine.)
Evan Minto notes that flexible grids created with CSS Grid’s repeat, auto-fill, and minmax are only intrinsically responsive (responsive to their container rather than the viewport) up to a point, because when the container width is narrower than the minimum width specified in minmax the grid children overflow.
Applying media queries to the grid is not a satisfactory solution because they relate to the the viewport (hence why Every Layout often prefer Flexbox to CSS Grid because it allows them to achieve intrinsic responsiveness).
However we’ll soon be able to suggest grid item width as a percentage of the parent container, avoiding the overflow problem. The new “CSS Math functions” to help us achieve this are min(), max() and clamp(). At the time of writing, these are only supported in Safari however Chrome support is in the pipeline.
Some simple but inspiring work here from Seattle-based web developer Katherine Kato. I really like the use of space, the typography, the colour palette and the use of CSS grid for layout.
Sometimes, for reasons unknown, we find that clicking or tapping an element just isn’t working. Here’s a CSS-based approach that might help.
I’ve recently encountered the scenario – usually in reasonably complex user interfaces – where I have an anchor (or ocassionally, a button) on which clicks or taps just aren’t working, i.e. they don’t trigger the event I was expecting.
On further investigation I found that this is often due to having an absolutely positioned element which is to some extent overlaying (or otherwise interfering with) our target clickable element. Alternatively, it may be because we needed a child/nested element inside our anchor or button and it is this element that the browser perceives as being the clicked or tapped element.
I’ve found that setting .my-elem { pointer-events: none; } on the obscuring element resolves the problem and get you back on track.
The HTML attribute aria-current allows us to indicate the currently active element in a sequence. It’s not only great for accessibility but also doubles as a hook to style that element individually.
By using [aria-current] as your CSS selector (rather than a .current class) this also neatly binds and syncs the way you cater to the visual experience and the screen reader experience, reducing the ability for the latter to be forgotten about.
Here’s a comprehensive and great-looking CSS reference featuring lots of examples.
While these days I normally reach for MDN Web Docs to keep me right on any given CSS feature, I’ve been thinking that with the recent explosion of new CSS features and syntax it’d be great to do a refresher course by working my way through a structured list of features—just like I did with Eric Meyer’s CSS: The Definitive Guide back in the day—and Codrops’ reference could be the perfect place.
Sliders (or carousels) are a fairly common practical requirement in web projects. Here, Chris Coyier shows us how far we can get in 2019 with HTML and CSS alone.
Automatically compiles SASS/SCSS files to .css and .min.css upon saving. You may also quickly compile all SCSS/SASS files in your project.
As I consider different ways in which to simplify my development stack and avoid excess tooling (much like Michelle Barker did), this might be worth a look.
I realised last night while watching a presentation by Lea Verou that I could streamline my CSS Grid layouts.
I’d been creating an overall page grid by setting body { display: grid; } then some grid areas but realised that this only worked for direct children and didn’t help with aligning more deeply nested elements to that outer grid.
For example in the case of the main header if I wanted its child logo, nav and search elements to snap to the body grid then I found myself having to duplicate the display: grid and grid-template-areas again on the header.
It didn’t feel very DRY but my understanding was that while we await subgrid, it was a necessary evil.
What I should have been using is display: contents.
If you set your header to display: contents then the parent (body) grid layout will apply to the header’s contents (logo, nav, etc) as if the header element (the “real” direct child of the grid) wasn’t there. This gives us good semantics without the need to redefine the grid on the header.
I was aware of the existence of display: contents but somehow it hadn’t sunk in because I’d only read about it in the abstract. Lea Verou’s explanation made all the difference. Cheers, Lea!
Update 4/5/2019
Frustratingly, I’ve learned that although we can apply this technique, we shouldn’t… or at least not for a while.
Due to a bug in all supporting browsers the property will currently also remove the element (header in our case) from the accessibility tree meaning that its semantics will be lost.
A while back I read a great SVG icon tip from Andy Bell which I’d been meaning to try and finally did so today. Andy recommended that for icons with text labels we set the width and height of the icons to 1em since that will size them proportionately to the adjacent text and additionally lets us use font-size to make any further sizing tweaks.
By applying width and height of 1em to our icon it is predictably sized by default.
It can now have its size further tweaked in CSS using font-size, for example with ems (where 1em = the font-size of the parent anchor element).
This technique requires the viewbox attribute being present on the svg.
Apply the width and height =1em as inline attributes on the svg. We could apply them using CSS, however the inline approach avoids potentially massive icons showing in cases where CSS doesn’t load.
To get the colour matching, apply fill="currentColor" as an inline attribute on the svg’s path.
Now, when you apply a hover colour to the anchor in CSS, the icon will just pick that up. Nice!
Applying inline-flex to the anchor makes the vertical-alignment of text and icon easier.
Apply aria-hidden to the icon because it’s mainly decorative so we don’t want it read out by screen readers.
Sometimes when coding a UI element you want a shadow around the whole box. However, most CSS box-shadow examples/tutorials tend to show inset box-shadows or ones that otherwise sit off to the side.
Here’s how to apply box-shadow to the whole box for a simple but nice effect.
Now this is great. Even though I’m now using CSS Grid fairly regularly there are still aspects of the syntax that I hadn’t fully wrapped my head around. This visual representation really helps!
<p id="top">
<a href="#bazinga">Go to the middle</a><br>
<a href="#1@#%^-bottom">Go to the bottom</a>
</p>
<p>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
</p>
<p id="bazinga"><a href="#1@#%^-bottom">Go to the bottom</a></p>
<p>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
</p>
<p id="1@#%^-bottom"><a href="#">Go back to the top</a></p>
html {
scroll-behavior: smooth;
}
@media screen and (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
Recently, we’d seen some articles suggest that things haven’t changed a great deal with select's styling limitations, but I decided to return to the problem and tinker with it myself to be sure. As it turns out, a reasonable set of styles can create a consistent and attractive select across new browsers, while remaining just fine in older ones too.
Here’s a breakthrough in the always-frustrating field of styling form elements. Scott Jehl of Filament Group introduces a new technique for styling the select element in a modern way without the need for a parent element, pseudo-elements, or javascript. Thanks, Scott!
Over the course of 2018 I’ve been trying to get the hang of CSS Grid.
I’d already become fairly adept at using Flexbox – a game-changing responsive layout technology which I love – but the prevailing wisdom suggested that I get with the program and learn this new system, too. At first I wondered whether I should even be using Flexbox at all any more; whether it was already old hat. After all, whereas Flexbox was essentially for laying out items in a single dimension, CSS Grid felt more important, being the web’s first ever purpose-built system for two-dimensional layout.
I have to admit that learning Grid did not come easy at first. Wrapped up in this new system is a whole load of new terminology, new units of measurement and new ways of thinking. Rachel Andrew’s book The New CSS Layout had been helpful but by autumn the concepts still weren’t fully clicking with me. Nor was I totally clear on the appropriate situations to use Grid. So I limited my first production forays to small components where I felt there was less risk of things going badly wrong.
A turning point came while attending Rachel Andrew’s talk Graduating to Grid in which she advised that when things start to feel complicated, remember that:
“It’s all just a grid of lines.”
For me, concentrating primarily on the grid-lines and not the stuff within and without helped simplify the overall concept and make all the supporting features click into place.
At the same conference, Eric Meyer acknowledged that a given layout challenge might be accomplished using either Flexbox or Grid, so in order to standardise your team’s approach it can be useful to set a rule such as:
“Grid for general layout; Flexbox for components.”
Jen Simmons also gave a presentation that included several code examples which used Grid at the layout level and Flexbox at the component level.
Now, I know that neither speaker was saying that it has to be split that way, however I personally liked the idea of applying this rule as a means of avoiding choice paralysis.
I was reminded that Flexbox makes developing responsive components such as navigation menus, fixed-height cards, lists of social icons etc much easier than they previously were with floats and absolute positioning. And for most of these components, because they are one-dimensional, CSS Grid would be overkill. So I realised: if it ain’t broke, don’t fix it. Don’t stop using Flexbox for things that it excels at.
I resolved to create a CSS Grid page layout on Fuzzy Logic, sticking to Flexbox for the components.
My basic idea was to start with a single-column layout for mobile phones then for wider screens break into a two-column layout… but with the logo sitting off “in space” to the left. Pretty simple, but complex enough to get me into:
using the fr unit for columns of whitespace;
using grid-template-areas to specify named grid areas for positioning my content, sidebar and footer sections; and
I started by knocking together a rough prototype, before fleshing things out and applying the layout to the main site. Depending on when you read this, you’ll see that layout in place now. If you want to check out the grid lines and areas I recommend using the Firefox (or Firefox Nightly) Grid Inspector.
Overall, it feels good to have taken the plunge into using CSS Grid for page layout, and it has given me confidence to explore further and try more interesting layouts. More to follow, I hope.
A handy tool for identifying colours – provided in numerous different CSS-ready formats – and creating a complimentary colour palette from an image you upload or provide as a URL.
Great resource from CSS Grid expert Rachel Andrew, with the Patterns and Examples sections which provide quick-start grid layouts being particularly handy.