Keith Cirkel shares his journey to contributing to web browsers as a web developer. If you’re curious about the learning curve, the standards process or simply, how to contribute to a browser without past experience, this episode is for you.
After attending Web Day Out and just missing Lola at the end, I read more about her and checked out her podcast.
Manuel sensed a general misunderstanding of what an interactive element is and what focusable really means. He wasn’t totally sure himself either, so did some research. It’s a long post but the summary is that:
an important characteristic of all interactive elements is they are natively focusable;
focusable doesn't necessarily mean sequentially focusable (tabbable). Some interactive elements including dialog are click-focusable, and these are not tabbable but can be focused programmatically or via click.
it’s also worth knowing that it's perfectly acceptable to place tabindex on a non-interactive element to aid with accessibility. But prefer applying it to semantic elements rather than divs.
At work, my talented colleague Anda and I have been taking a fresh look at modal dialogues with a view to modernising relevant design system components. During this project I’ve expanded my knowledge of the HTML dialog element, especially the nitty-gritty of using it in practice.
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.
When asking users for numbers and dates, which HTML form elements should we use?
When asking the user for numeric information it might feel obvious to use the HTML input type meant for that purpose, namely number.
However the UK GDS wrote in 2020 that they had switched to using inputs of type text, with inputmode set to numeric. This was after conducting tests which had revealed a variety of usability and accessibility issues.
In the same article a reader questioned why GDS’s use of text inputs also extended to gathering dates (a subset of numbers) when there is a dedicated input type date for that purpose. GDS answered that there are accessibility and usability problems with browser implementations of <input type"date"> and linked to Hassell Inclusion’s 2019 article on date inputs as evidence.
It’s also worth reiterating that the Hassell article is from 2019 and the GDS one from 2020, and four or five years is a long time in browser support.
So what should we do, and how should we make the decision? I’m gonna circle back to this and update it with some answers soon, once I’ve worked them out.
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.
An interesting article which helps the author – and his readers – understand some of the lesser-used and more obscure HTML elements.
While Patrick confesses he is still learning certain things and therefore I won’t regard his implementations as gospel in the way I might an article by someone with greater HTML and accessibility expertise such as Adrian Roselli, I see this as another useful resource to help me when deciding whether or not an HTML choice is the semantic and or correct tool for a given situation.
Adrian tests how blockquotes, marked up in a variety of ways, are announced in different screen readers.
He concludes that his personal choice is as follows:
<main>
<!-- other content -->
<blockquote>
<p>A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools.</p>
<footer>— <cite>Douglas Adams, <a href="https://en.wikipedia.org/wiki/Mostly_Harmless">Mostly Harmless</a></cite></footer>
</blockquote>
<!-- other content -->
</main>
He avoids the citeattribute completely because it creates noise in JAWS, and recommends against using figure with figcaption because it results in unnecessarily verbose and duplicate announcements.
In his chosen approach the footer is used mainly as a sensible styling hook, since in the context of a main (as opposed to as a direct child of body) it is not regarded a landmark and is strictly presentational. The cite element has semantic intent – it’s the element for marking up the title of a cited creative work – even if those semantics are not always exposed to users.
So there’s an action for my team at work, because our blockquote component currently uses figure and figcaption. Perhaps at the time of build we took advice from one of the MDN or W3C pages which Adrian has now shown weren’t ideal.
In web-based products from e-commerce stores to email clients to accounting software you often find index pages where each item in a list (or row in a table) has a Delete option. This is often coded as a link… but it shouldn’t be.
I liked this comment by Rails developer Dan where he advises a fellow Rails developer that to create his Delete control he should use a form rather than a link, via Rails’s button_to method.
Dan mentions that in the past Rails UJS set an unsdesirable historical precedent by including a pattern of hijacking links for non-GET reqests.
A GET request is a visit, it says “show me this” and it’s idempotent. When you make the same request it’ll show the same thing.
If on the other hand you want a control that performs an action (in this case request an entity to be deleted) then the appropriate HTML element is usually a button, and in this case a submit button within a form.
Relatedly, Jeremy Keith previously wrote about how to use request methods properly in his excellent post Get safe.
Two lovely new websites (or website updates) appeared on my radar this last week that I wanted to note here for future front-end inspiration.
Vitaly Friedman’s Smart Interface Patterns has had some lovely animation and component work from Clearleft alumni Cassie Evans and Trys Mudford. Given Vitaly’s obsession with creating accessible, user-friendly components and the collaborators he has on board, I expect this site to be choc-full of well crafted nuggets for reference! It looks ace, too.
I noted a while ago that the W3C had a new Design System, and now the W3C has a new website in beta too. I imagine it might use components from that Design System alongside other carefully-considered patterns of markup, style and behaviour.
My work colleague Ryan recently drew my attention to the new HTML search element. This morning I read Scott O’Hara’s excellent primer. Scott worked on implementing <search>, and his article cleared up my questions around what it is and when we can start using it.
Firstly <search> is not a “search input” – it’s not a replacement for any existing input elements. Instead it’s a native HTML element to create a searchlandmark, something that until now we could only achieve by applying role="search" to another element.
Landmarks are an important semantic structure allowing screen reader users to orient themselves and jump to important areas of a web page. Existing landmark-signalling elements you might know include <header>, <main>, <footer>. So you would use <search> to wrap around a search function, thus providing additional accessibility. And it lets you do so with a native HTML element instead of re-purposing another element by adding ARIA properties, per the first rule of ARIA use. It’d look something like this:
So as Scott himself admits:
To be brutally honest, this is not the most important element that’s ever been added to the HTML specification. It is however a nice little accessibility win.
Do I have a use for this?
If you have a search function or search page and currently miss the opportunity to offer a search landmark you could do so and improve the user experience.
Can I use the <search> element today?
As Scott mentions, it’s not yet available in browsers (although it likely will arrive soon). So if you added <search> (just as I’ve typed it there) to a page, it wouldn’t currently create a search landmark. So you could wait for a while before using the element. Alternatively, because HTML’s design is intentionally geared toward a progressive enhancement mindset, you could take Jeremy Keith’s approach and safely use the following today:
...
Jeremy knows that when browsers encounter an HTML element they don’t know, they don’t break but rather treat it as an anonymous element and carry on. So he includes <search> to start adopting the new element today, but bolts on role=search temporarily to manually provide the landmark until browsers understand search. He’ll then remove the role=search part once support for search is widespread.
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)
However first I think we’d need to make an informed decision regarding our satisfaction with support, based on the updated advice in Scott O’Hara’s article Having an Open Dialog.
(Accessibility expert Scott O’Hara has been diligently testing the dialog element for years.)
I personally think it’s time to move away from using custom dialogs, and to use the dialog element instead.
That’s an important green-light!
And this of course means that we can stop DIYing modal dialogues from divs plus super-complicated scripting and custom ARIA, and instead let a native HTML element do most of the heavy lifting for us.
From a Design System perspective, I’d previously suggested to my team that when we revisit our Modal component we should err toward a good custom dialogue library first, however I’m now likely to recommend we go for native dialog instead. Which is great!
People have used the HTML title attribute to achieve a native “tooltip” effect for many years. However accessibility experts have recommended that we should avoid this practice, and here I summarise my research on the topic.
Renowned accessibility solutions provider The Paciello Group recommend the title attribute should almost always be avoided. It causes problems for lots of different usage contexts (keyboard, touch device, screen readers). The only place where I can see that it is still helpful is on iframe. It was beneficial on form inputs in cases where a visible text label would be redundant and we want to provide our control with a programmatically associated label, however we now have aria attributes which do a better job.
So on anything other than iframe the title attribute is undesirable. To back this up, at work my team recently received the following accessibility feedback from Tetralogical when they reviewed one of our tables.
The Edit and Delete links use the title attribute to provide additional context for each link. The title attribute can be unreliable (for example, in testing VoiceOver announces the title in French). Provide additional context using the aria-describedby attribute to reference the name or reference value of the item.
Whether I’m thinking about inclusive hiding, hamburger menus or web components one UI pattern I keep revisiting is the disclosure widget. Perhaps it’s because you can use this small pattern to bring together so many other wider aspects of good web development. So for future reference, here’s a braindump of my knowledge and resources on the subject.
A disclosure widget is for collapsing and expanding something. You might alternately describe that as hiding and showing something. The reason we collapse content is to save space. The thinking goes that users have a finite amount of screen estate (and attention) so we might want to reduce the space taken up by secondary content, or finer details, or repeated content so as to push the page’s key messages to the fore and save the user some scrolling. With a disclosure widget we collapse detailed content into a smaller snippet that acts as a button the user can activate to expand the full details (and collapse them again).
Adrian Roselli’s article Disclosure Widgets is a great primer on the available native and custom ARIA options, how to implement them and where each might be appropriate. Adrian’s article helpfully offers that a disclosure widget (the custom ARIA flavour) can be used as a base in order to achieve some other common UI requirements so long as you’re aware there are extra considerations and handle those carefully. Examples include:
link and disclosure widget navigation
table with expando rows
accordion
hamburger navigation
highly custom select alternatives when listbox is innapropriate because it needs to include items that do not have the option role
Heydon Pickering’s Collapsible sections on Inclusive Components is excellent, and includes consideration of progressive enhancement and an excellent web component version. It’s also oriented toward multiple adjacent sections (an accordion although it doesn’t use that term) and includes fantastic advice regarding:
appropriate markup including screen reader considerations
how best to programmatically switch state (such as open/closed) within a web component
how to make that state accessible via an HTML attribute on the web component (e.g. <toggle-section open=true>)
how that attribute is then accessible outside the component, for example to a button and script that collapses and expands all sections simultaneously
There’s my DIY Disclosure widget demo on Codepen. I first created it to use as an example in a talk on Hiding elements on the web, but since then its implementation has taken a few twists and turns. In its latest incarnation I’ve taken some inspiration from the way Manuel Matuzovic’s navigation tutorial uses a template in the markup to prepare the “hamburger toggle” button.
I’ve also been reflecting on how the hidden attribute’s boolean nature is ideal for a toggle button in theory – it’s semantic and therefore programattically conveys state – but how hiding with CSS can be more flexible, chiefly because hidden (like CSS’s display) is not animatible. If you hide with CSS, you could opt to use visibility: hidden (perhaps augmented with position so to avoid taking up space while hidden) which similarly hides from everyone in terms of accessibilty.
As it happens, the first web component I created was a disclosure widget. It could definitely be improved by some tweaks and additions along the lines of Heydon Pickering’s web component mentioned above. I’ll try to do that soon.
Troubleshooting
For some disclosure widget use cases (such as a custom link menu often called a Dropdown) there are a few events that typically should collapse the expanded widget. One is the escape key. Another is when the user moves focus outside the widget. One possible scenario is that the user might activate the trigger button, assess the expanded options and subsequently decide none are suitable and move elsewhere. The act of clicking/tapping elsewhere should collapse the widget. However there’s a challenge. In order for the widget to be able to fire unfocus so that an event listener can act upon that, it would have to be focused in the first place. And in Safari – unlike other browsers – buttons do not automatically receive focus when activated. (I think Firefox used to be the same but was updated.) The workaround is to set focus manually via focus() in your click event listener for the trigger button.
At work there are plans afoot to reconcile various differing Autocomplete implementations into a single, reusable component. So far there’s been a written audit presenting all instances and how they differ in functional and technical respects. There’s also been design work to identify visual commonalities and avoid future inconsistencies. I’d now like to add another perspective: an investigation into which HTML materials and (if necessary) ARIA supplements are appropriate to ensure we build something accessible and resilient.
My experience is that to achieve the right result, HTML semantics and related concerns can’t just follow and bend to spec and visual design goals, but rather must influence the setting of those goals.
I’ll flesh out my findings in due course, but for now here are the key resources I’ve identified and plan to dig deep into.
ARIA Listbox lets you create a DIY thing that has the same roles and semantics as a <select> but where you have greater stylistic control. There are different ways to implement a Listbox.
Datalist is the native HTML version of a combo box. A combo box is essentially a <select> with a text field. Datalist is announced by screen readers in different ways but as far as I can gather these are quirky rather than terrible. I found a nice Twitter thread on DataList which not only shows off its function but also includes a promising accessibility-related comment from Patrick H Lauke of Tetralogical. The drawback, because Datalist is native HTML, is that its options are not stylelable.
ARIA Combobox is a pattern that combines ARIA combobox, textbox and listbox roles, and the benefit it brings is to allow a level of custom design that you couldn’t achieve with Datalist.
Autocomplete (not to be confused with the HTML autocompleteattribute) describes a control which provides users with suggestions that may not be available in the DOM already… for example when you fetch options via Ajax in reponse to what the user types.
And for advice on whether or not to go with a native select or a custom control, and how best to implement listbox and combobox if that’s your choice, Adrian points to the following resources from Sarah Higley:
I also see that GOV.UK have marked a possible Autocomplete component as one of their next priorities to review. Their Autocomplete discussion thread includes examples and research and will be really helpful.
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.
My team will soon be refactoring our modal dialogue component. Ours has a few deficiencies, needs better developer experience and documentation, is not built to our Design System component standards, and could use a resilience boost from some progressive enhancement.
For a long time the best – meaning accessible, framework-agnostic, feature-packed – modal implementations were custom. Specifically:
However with recent browser advances (especially from Safari), there’s an argument that the time has now come that we no longer need custom solutions and can go native. So we might reach for the native <dialog> HTML element.
However first I think we’d need to make an informed decision regarding our satisfaction with support, based on the updated advice in Scott O’Hara’s article Having an Open Dialog.
Additionally we should definitely be keeping one eye on proposals around the exciting new togglepopup and popup attributes which promise the holy grail of entirely HTML-powered modal dialogues with no JavaScript dependency.
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.
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.
“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)
Here’s an interesting development in the block link saga: GOV.UK have introduced one (named .chevron-card) on their Homepage, citing how it’ll improve accessibility by increasing mobile touch targets. It’s not yet been added to their Design System while they’re monitoring it to see if it is successful. They’ve chosen the approach which starts with a standard, single, non-wrapping anchor then “stretches” it across the whole card via some pseudo elements and absolute positioning magic. I’m slightly surprised at this choice because it breaks the user’s ability to select text within the link. Really interested to see how it pans out!
Lovely write-up, & great rationale re. larger mobile tap targets! I’ve wrestled with “block links” & found that each approach has issues so it’s v. interesting that you chose the route that impacts text selection. Is that the lesser of the evils? Keen to hear how it pans out!
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.
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
In this journal entry, Jeremy Keith argues that when it comes to accessibility testing it’s not just about finding issues—it’s about finding the issues at the right time.
Here’s my summary:
Accessibility Audits performed by experts and real Assistive Technology users are good!
But try to get the most out of them by having them focus on the things that you can’t easily do yourself.
We ourselves can handle things like colour contrast. It can be checked at the design stage before a line of code is written.
Likewise HTML structure such as ensuring accessible form labels, ensuring images have useful alt values, using landmarks like main and nav, heading structure etc. These are not tricky to find and fix ourselves and they have a big accessibility impact.
As well as fixing those issues ourselves we should also put in place new processes, checks and automation if possible to stop them recurring
As for custom interactive elements (tabs, carousels, navigation, dropdowns): these are specific to our site and complicated/error-prone by nature, so those are the things we should be aiming to have professional Accessibility Audits focus on in order to get best value for money.
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.
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.
As most of us know, the HTML alt attribute is for providing “alternate text” descriptions of images to help ensure people do not miss out on information conveyed by graphics. This can help people using assistive technology such as screen readers, and in situations where images are slow or fail to load.
The article made some interesting points and even though I’ve been using the alt attribute for years I found three common cases where I could improve how I do things.
Avoid starting with “photo of…”
Don’t begin alternative text with “photo of…” or “picture of…”. Assistive technologies already indicate the role of the element as an “image” or “graphic”. Redundancy makes for a poor user experience.
Avoid including the word “logo” in logo images
If the image is a company’s logo, the alt should be the company’s name. Adding the word “logo” as part of the alternative text is neither necessary nor useful. (One thing I found helpful here is to think of the way I, as a sighted person, perceive Apple’s logo. I just think “Apple”, not “Apple’s logo”, so I guess the same principle applies.)
If using an image multiple times on the page, tailor the alt text
Using an image several times in a website doesn't necessarily mean the alt attribute should be the same for each instance. For example, when using a logo in the website’s header this often doubles as a link back to the home page. In this example, the alt would be most useful as “Apple - Homepage”. If that same logo were used in the footer of the site alongside the text “Apple, copyright 20XX”, then the logo should have an empty alt (alt="") so as to avoid creating a redundant announcement of the company’s name.
Hidde de Vries explains why an HTML heading should never be immediately followed by another.
When you use a heading element, you set the expectation of content.
I have always prided myself on using appropriate, semantic HTML, however it’s recently become clear to me that there’s one thing I occasionally do wrongly. Sometimes I follow a page’s title (usually an h1 element) with a subtitle which I mark up as an h2. I considered this the right element for the job and my choice had nothing to do with aesthetics.
HTML headings are essentially ”names for content sections”. On screen readers they operate like a Table of Contents – one can use them to navigate to content.
Therefore I now reckon I should only use a hx heading when it will be immediately followed by (non-heading) content – paragraphs and so on – otherwise I should choose a different element.
I should probably mark up my subtitles as paragraphs.
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.
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).
Here’s a neat trick. You can use an emoji as a favicon! I’ve written previously about how to do favicons properly, but for a short-lived hack project you tend to just need something quick and dirty. Chris Coyier has also shared a nice lil’ Codepen website showing the technique in action.
Now that all modern browsers support SVG favicons, here's how to turn any emoji into a favicon.svg:
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.
In cases of emergency, many organizations need a quick way to publish critical information. But existing (CMS) websites are often unable to handle sudden spikes in traffic.
Fantastic effort by Max Böck here, stepping up during the COVID-19 pandemic to provide this Eleventy template for organisations to use to publish critical information as lean, resilient, static HTML pages.
In this post we have seen that with just a sprinkling of HTML attributes we can improve the login experience for our users, particularly on mobile devices.
By adding certain attributes to the HTML input element – such as inputmode, pattern and autocomplete="current-password" – we can improve the user experience when logging in.
Here’s Dave Rupert, frustratedly rounding up the accessibility shortfalls in browser implementations of native HTML elements.
I’ve always abided in the idea that “HTML is accessible by default and then we come along and mess it up”. But that’s not always the case. There are some cases where even using plain ol’ HTML causes accessibility problems.
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)
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)
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.
Knowing how best to serve, size and format favicons and other icons for the many different device types and operating systems can be a minefield. My current best practice approach is to create a 260px × 260px (or larger) source icon then upload it to Real Favicon Generator.
This is the tool recommended by CSS-Tricks and it takes care of most of the pain by not only generating all the formats and sizes you need but also providing some code to put in your <head> and manifest.webmanifest file.
This slider/carousel certainly looks nice, and I like author David DeSandro’s work, having taken inspiration from his 3d Card Flip tutorial for a recent project. I’d just like to dig into it a little further to see how it fares in terms of accessibility before using it in the wild.
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.
I previously noted Keith J Grant’s article on the HTML dialog element which promised a native means of handling popups and modal dialogues. I’ve not yet used dialog in production, partly because of spotty browser support (although there is a polyfill) but also partly because—for reasons I couldn’t quite put my finger on after reading the spec—it just didn’t feel like the finished article.
Fast forward to March 2019 and Scott O’Hara has written an excellent piece describing why it’s still not ready. There are a combination of factors: lack of browser support, reliance on JavaScript; and multiple accessibility issues.
The fairly-recently added <details> element is a great, native HTML way to toggle content visibility.
<p>Lorem ipsum dolor sit amet.</p>
<details>
<summary>System Requirements</summary>
<p>Requires a computer running an operating system. The computer
must have some memory and ideally some kind of long-term storage.</p>
</details>
In all my years of spinning up “HTML Typographic Elements” lists or pages as a reference for designers, I didn’t realise that the W3C provide the very thing I needed in their HTML Element Sampler. These pages provide comprehensive dummy content covering all the main typographic elements which is really handy when designing a website’s typographic styles and pattern library.
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!
Introducing dialog: a new, easier, standards-based means of rendering a popup or modal dialogue.
The new element can be styled via CSS and comes with Javascript methods to show and close a dialog. We can also listen for and react to the show and close events.
Although currently only supported in Chrome, the Google Chrome dev team have provided a polyfill which patches support in all modern browsers and back to IE9.