<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ingvild Forseth on Medium]]></title>
        <description><![CDATA[Stories by Ingvild Forseth on Medium]]></description>
        <link>https://medium.com/@forsethingvild?source=rss-c8803f8258c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zue3xZdxyUi-cZIkhjpVcQ.jpeg</url>
            <title>Stories by Ingvild Forseth on Medium</title>
            <link>https://medium.com/@forsethingvild?source=rss-c8803f8258c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:27:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@forsethingvild/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Book Review: Web Accessibility Cookbook by Manuel Matuzovic]]></title>
            <link>https://forsethingvild.medium.com/book-review-web-accessibility-cookbook-by-manuel-matuzovic-a34cb22cb742?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34cb22cb742</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[manuel-matuzovic]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 14:24:07 GMT</pubDate>
            <atom:updated>2026-10-27T14:33:17.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*QG6DPCI2PBSCqAGCKVmJRg.jpeg" /><figcaption>Book cover image from <a href="https://www.amazon.co.uk/Web-Accessibility-Cookbook-Inclusive-Experiences/dp/1098145607">here</a>.</figcaption></figure><p>The web should be accessible for everyone. People with impaired vision or any other disabilities should of course be able to use the web — we all should be able to to fill out governmental schemas, read news or maybe buy a book or some clothing online. And who knows, maybe you will experience <a href="https://www.joshwcomeau.com/blog/mindbody/">a disibility for a limited time of your life</a>. Making web pages accessible should therefore be a given for web developers.</p><p>Still, the <a href="https://webaim.org/projects/million/">WebAIM Million</a> 2024 report shows that of the top 1 million most visited websites 44% of them contain empty links and 28.2% contain empty buttons, which means screen reader users will not know to where these links will take them or what will happen when they click those buttons ([1], p. 70, 104).</p><p>Masters in web development like <a href="https://rachelandrew.co.uk/">Rachel Andrews</a> (content lead @Google) and <a href="https://chriscoyier.net/">Chris Coyier</a> (creator of CodePen) have given their praise for the book <a href="https://accessibility-cookbook.com/">Web Accessibility Cookbook</a> by <a href="https://matuzo.at/about-me">Manuel Matuzovic</a> (who has given at least two great talks at the CSS Day conference, look them up! :))</p><p>Thus, the book was an <em>easy</em> pick for me, and I wanted to let you know if it is worth a read. Spoiler alert, the answer is <em>yes</em>, but follow along if you want some more details of the book, if you are contemplating picking it up or not.</p><p><em>Disclaimers</em>: This article is mainly an attempt to enforce my own learning by making notes as I go. Before I published this post, I made sure the author of the book was okay with me publishing it (by sharing the post in advance).</p><h3>My Immediate Thoughts of the Book</h3><p>The book is concise and straight to the point. It works great as a reference book if you are an experienced web developer (and also serves as a good reminder). But it also works for beginners to web development — it just has to become a more thorough read.</p><p>It also strikes me how much knowledge the author has, or at least how much he has obtained writing this book. From every command in the different screen reader technologies (JAWS, VoiceOver etc.) to the <em>exact</em> usage of the different aria attributes. And he is so generous that he shares it all with us in this book.</p><p>The book is ~350 pages, and I as a web developer with 6 years experience spend 5+ hours getting through it.</p><h3>The Book’s Structure</h3><p>This is the topic of each chapter (12 in total):</p><ul><li>Structuring Documents</li><li>Structuring Pages</li><li>Linking Content</li><li>Performing Actions</li><li>Styling Content</li><li>Managing Focus</li><li>Navigating Sites</li><li>Toggling Content Visibility</li><li>Constructing Forms</li><li>Filtering Data</li><li>Presenting Tabular Data</li><li>Creating Custom Elements</li><li>Debugging Barriers</li></ul><p>Each subchapter has the subheadings “Problem”, “Solution” and “Discussion” — a <em>very</em> tidy organization of the book’s organization that makes it easy to use as an encyclopedia when meeting those exact accessibility (a11y) challenges later on.</p><h3>The Most Important Takeaways</h3><p>Here are some of the things I learned from the book, or just a reminder of something that I want to remember:</p><h4>About Structuring Documents:</h4><ul><li><em>“Unique titles </em>[i.e. the &lt;title&gt; element]<em> helps to distinguish one page from the other if multiple tabs of the same site are open.”</em> ([1], p. 8)</li><li>Best loading strategy as advised by web performance expert Harry Roberts in the &lt;head&gt; element is the following: Preconnect links, async Javascript, synchronous JavaScript, preload links, deferred JavaScript, prefetch links and prerender links ([1], p. 13)</li></ul><h4>About Structuring Pages:</h4><ul><li>Landmarks are parts of your page important enough that your user should be able to navigate directly to them, and role=”region&quot; promotes a generic element to a landmark (use sparingly). ([1], p. 37)</li></ul><h4>About Linking Content:</h4><ul><li>When to use a link vs. button: Use a link when the element takes the user somewhere. Use a button if the element submits a form or runs Javascript. ([1], p. 53)</li><li><em>“Don’t use </em><em>box-shadow alone for link or focus styling because shadows will not be displayed in forced-color mode. ([1], p. 58)</em></li><li>According to WCAG 2.2 touch targets should be at least 24 x 24 CSS pixels ([1], p. 60)</li><li>Download links should containt the following info: What information does it contain, which format and how large is it. E.g. <em>“Download the sustainability report 2022 (PDF, 29MB)”. </em>([1], p.62)</li><li>It is possible to prefill the subject and body using an email link: &lt;a href=mailto:email@email.com?subject=...&amp;body=...&gt;email@email.com&lt;/a&gt; ([1], p. 66)</li><li>SVGs can have a &lt;title&gt; element inside. Reference it using aria-labelledby on the &lt;svg&gt; tag to make it accessible ([1], p. 68)</li><li>Images can be divided into three categories: Informative (should have an alt text, e.g. describing how what is photographed looks), decorative (can be hidden unless they somehow contribute to the atmosphere of the page) and functional (rather describe the action it initiates when clicking on it) ([1], p. 70–71)</li><li>Usability and a11y experts advise <em>not</em> to open links in new tabs or windows (one of the strongest arguments against it is that you take away the user’s ability to choose for themselves) ([1], p. 73–74).</li></ul><h4>About Performing Actions:</h4><ul><li>For a card component with multiple links, the following solution is recommended: If it is okey the text inside the card is not selectable: Add a pseudoelement to the link to make the whole card clickable, and make other links clickable by using z-index. If selectable text is important (solution requires JavaScript): <a href="https://inclusive-components.design/cards/">Use the </a><a href="https://inclusive-components.design/cards/">mousedown and </a><a href="https://inclusive-components.design/cards/">mouseup events to detect if the user clicked or selected the card’s text as Heydon Pickering describes in this article</a>, or <a href="https://css-tricks.com/block-links-the-search-for-a-perfect-solution/">the selection API to detect it as described by Vikas Parashar in this article</a> ([1], p.89–90)</li><li>“<em>The </em><em>&lt;button&gt; has two main use cases: submitting a form and running Javascript </em>(set type=”button”)<em>” </em>([1], p.100)</li><li>WCAG has six specific requirements for a button to be accessible and provide great UX: (1) Convey the button role (i.e. use preferably &lt;button&gt;, or role=”button&quot;) (2) It has visible text or a text alternative (3) It communicates it’s state (e.g. aria-pressed=&quot;true&quot;or aria-expanded=”false together with aria-controls=&lt;id of controlled element”) or the state of any other element it controls (4) It is recognizable as a button (because according to <a href="https://lawsofux.com/jakobs-law/">Jakob’s law</a>, users spend most time on other web pages than your own, so it should look similar to how it looks on the rest of the internet). (5) It’s colors must have enough contrast (both the text color to the background, and it’s background color to adjacent colors) (6) It must be tabbable, and allow click, touch and key events (Enteror Space) ([1], p. 101–102)</li><li><a href="https://adrianroselli.com/2020/01/my-priority-of-methods-for-labeling-a-control.html">Recommended priority order for labelling buttons by Adrian Roselli</a>: 1) Native HTML techniques (e.g. just name your button informative and concise) 2) aria-labelledby pointing to existing visible text 3) Visibly hidden content 4) aria-label ([1], p. 105)</li><li>Don’t create “fake” buttons, i.e. even though it might not look like a button in the design spec, use the &lt;button&gt; tag so it is focusable by keyboard etc. It means you can’t tie your button-CSS to the &lt;button&gt; tag.</li><li>Or, if the button-CSS is tied to the &lt;button&gt; tag, reset all properties using all: unset (sets all properties to their initial value according to the spec, see e.g. on MDN) or all:inherit (keeps inherited values from the parent, e.g. font-size) ([1], p.108-109)</li><li><em>“Use the </em><em>aria-expanded attribute on a </em><em>&lt;button&gt; element to indicate whether a grouping element it controls is expanded or collapsed. </em>[…] <em>Users should understand from the button text which element the button controls. </em>[…]<em> avoid generic terms like show/hide. </em>[…] <em>you must set it to true or false. </em>[…] <em>if you don’t set the attribute, the button doesn’t control anything. </em>[…]<em> The</em><em>aria-controls attribute </em>[…]<em> is a list of one or more id references.” </em>([1], p. 114)</li><li><em>“A toggle button is similar to a checkbox </em>[…]<em> a checkbox conveys only a state </em>[…]<em>, whereas a button performas an action. When users click a toggle button, they expect something to happen. </em>[…] aria-pressed<em> indicates the current pressed state of toggle buttons. </em>[…] <em>You’re not supposed to use </em><em>aria-checkedon a button with </em><em>role=”button&quot;, but you can use it on a switch </em>[<em>role=”switch&quot;</em>]. […] <em>Switches are </em>[however]<em> a problematic pattern in terms of user experience. </em>[…]<em>One reason is that their state isn’t always straightforward. </em>[…] <em>instead </em>[…] <em>use a checkbox.</em> […] <em>If you decide to use them, test them thoroughly with users, including those who use screen readers. “ </em><a href="https://adrianroselli.com/2019/03/under-engineered-toggles.html">Read about how to implement toggles by Adrian Roselli here</a>. <a href="https://axesslab.com/toggles-suck/">Read about why switches/toggles are problematic by Joel Homberg here.</a> ([1], p. 115, 243)</li><li>How to implement a menu button (see code ⬇️). <em>“The </em><em>aria-haspopup attribute indicates that a button controls another interactive element. Most screen readers announce the type of pop-up element. The attribute supports seven values: true, false, menu, dialog, grid, listbox and treee, indicating the that referenced element has the respective role </em>[they have to match]<em>. true is the same as menu.</em>([1], p. 113, 115)</li></ul><pre>&lt;button type=&quot;button&quot; aria-haspopup=&quot;menu&quot; aria-exapanded=&quot;false&quot; id=&quot;button_settings&quot;&gt;<br>  Settings<br>&lt;/button&gt;<br>&lt;ul role=&quot;menu&quot; aria-labelledby=&quot;button_settings&quot; hidden&gt;<br>  &lt;li role=&quot;none&quot;&gt;&lt;button role=&quot;menuitem&quot;&gt;Menu item 1&lt;/button&gt;&lt;/li&gt;<br>  ...<br>&lt;/ul&gt;<br><br>&lt;style&gt;<br>  [aria-expanded=&quot;true&quot;] + ul {<br>    display: block;<br>  }<br>&lt;/style&gt;</pre><p>Belonging JavaScript:</p><pre>const button = document.querySelector&lt;&quot;button&quot;&gt;;<br>button.addEventListener(&quot;click&quot;, e =&gt; {<br>  const isExpanded = button.getAttribute(&quot;aria-expanded&quot;) === &quot;true&quot;;<br>  button.setAttribute(&quot;aria-expanded&quot;, !isExpanded);<br>});</pre><ul><li>Why disabled buttons are bad?: Nothing happens when they are clicked, i.e. the user gets no feedback. Disabled buttons are not focusable, so somone using a keyboard navigation might not even know it exists. WCAGs minimum contrast rule does not apply to it, and not everyone will understand it is disabled, making it a frustrating experience when trying to click it. ([1], p 116)</li><li><em>“Don’t disable buttons. Users should always be able to interact with them and get feedback. </em>[..]<em> instead </em>[…] <em>(1) Use clear labels fofr your input fields (2) Add hints and descriptions when label alone isn’t clean enough (3) Split complex forms into mutiple steps or pages </em>[…] <em>(4) Always enable buttons and validate input on submit (5) Give clear error messages. When the user presses the button, provide them with a list of errors that point to the respective fields, or move focus to the erroneous filed if there’s only one. </em>([1], p. 116–117)</li></ul><h4>About Styling Content:</h4><ul><li><em>“Don’t use color alone to indicate an action, prompt a response, visualize a change of state or distinguish a visual element. </em>[…]<em> E.g. use an error message, an x icon, the color red and the </em><em>aria-invalid=”true&quot; attribute </em>[…] <em>conveying that something is wrong. </em>([1], p. 120)</li><li><em>“According to the World Health Organization (WHO) 39 million people worldwide are blind and 246 million have low vision. </em>([1], 121)</li><li><em>“WCAG’s minimum requirements for color contrast are:” </em>(1) Regular text ratio 4.5:1 (2) Regular text ≥ 24px and bold text ≥ 19px:: 3:1 (3) Logos, brand names and decorative elements don’t have any requirement ([1], p. 121)</li><li>The current contrast algorithm used by WCAG have some criticism: It does not take hum perception into account, nor the font’s characteristics (like size and weight), and treats front and background color the same (even though surounding color affects perception). ([1], p. 122)</li><li>APCA, a new contrast algorithm, is in the WCAG 3.0 draft, but it is not ready yet, and also APGA still have some open questions. ([1], p. 122)</li><li>There are 7 browser and OS preferences you can detect with media queries: Dark mode (prefers-color-scheme: dark), increased contrast (prefers-contrast: more), forced colors (i.e high-contrast themes, forced-colors: active), inverted colors (inverted-colors: inverted), JavaScript support (scripting: enabled), reduced transparency (prefers-reduced-transparency: reduce) and reduced motion (prefers-reduced-motion: reduce). ([1], p. 125)</li><li><em>“… content is the reason we create websites to begin with. </em>[…]<em> That means shipping text and HTML with as few dependencies as possible. </em>[…]<em> T hat works well because HTML and CSS are designed to be error-tolerant </em>[…] <em>feature detection in CSS </em>[(@supports (&lt;css-property&gt;: &lt;value&gt;))]<em> and JavaScript is another excellent way to control your layers. </em>([1], p. 127)</li><li>Testing forced-color mode is only possible on Windows for the entire OS, but you can use browser settings or developer tools. Tweak any styling that makes any element become difficult to see. Usually the UI works well by default, so ideally there should be little to do. Remember, it is about visibility, not beauty. ([1], 130)</li><li>It is bad practice setting font-size, line-height and max-width using px. Instead, use rem for font-size, a multiplier for line-height and e.g. px or ch (which is the width of the glyph 0 in the font) for max-width ([1], p. 134, 136)</li><li>60–80 ch per line is a good rule of thumb (but depends on the typeface, font-size and language) ([1], p. 137)</li><li>px values for properties like margin, padding, border, box-shadow, text-shadow, border-radius can be better. <a href="https://ashleemboyer.com/blog/why-you-should-use-px-units-for-margin-padding-and-other-spacing-techniques/">Ashlee M. Boyer argues in “Why You Should Use px Units for margin, padding, &amp; Other Spacing Techniques”</a> it is because when spacing grows, it can take up vital real estate. Testing what works for your app is necessary. ([1], p. 137)</li><li>A users xooming options: (1) Desktop browsers: Change base font-size or cmd/ctrl +/- (2) Mobile browsers: Change text size or zoom the entire page (depends on OS and browser (3) Pinch-zooming using a screen or trackpad, depending on OS and browser that supports it ([1], p. 138)</li><li><em>“… it’s still worth preferring </em><em>em </em>[in media queries, e.g. @media(min-width: 60em] <em>over </em><em>px, because users who have changed the base font size in their browser benefit from them </em>[(there was a time when this had much more importance though)]<em>.” </em>([1], p. 141)</li><li><a href="https://pimpmytype.com/font-size/"><em>“UI designer and typographer Oliver Schöndorfer </em>[…] <em>recommends increasing the font-size with the screen size, because the larger the screen, the larger the distance between the eyes and the device.”</em></a><em> </em>([1], p. 141)</li><li><em>“Larger line height are usually more visually appealing and help people with cognitive disabilities. A line height of 1.5 to 2 allows them to start a new line more easily after finishing the previous one. The rule of thumb mainly appies to running text. Line heights should decrease as the font size decreases.” </em>([1], p. 141)</li><li>Keep in mind that when using pointer-events: none on an interactive elemnt, the user can still focus on it using the keyboard, but it cannot be activated using the mouse or Enter , which is not conveyed semantically by a screen reader (i.e. it does not know it cannot be activated). ([1], p. 145)</li><li><em>“Animations on the web </em>[…] <em>can cause nausea, dizziness and headaches </em>[…] <em>Fading transitions or slight movements aren’t usually troublesome.” </em>E.g. let the default animation be “fade”, and if the user has no preferences for reduced motion, let the animation be “move”. ([1, p. 145, 146 148])</li><li>Examples of showing a gif or a jpg depending on the user’s preferences: ([1], p. 147)</li></ul><pre>&lt;picture&gt;<br>  &lt;source srcset=&quot;object.jpg&quot; media=&quot;(prefers-reduced-motion: reduce)&quot; /&gt;<br>  &lt;img src=&quot;object.gif&quot; alt=&quot;&lt;some text&quot; &gt;<br>&lt;/picture&gt;</pre><ul><li>Using JavaScript to pick scroll behaviour depending on user preferences: ([1], p. 147)</li></ul><pre>const button = document.querySelector(&quot;button&quot;);<br>const motionQuery = matchMedia(&quot;(prefers-reduced-motion: no-preference)&quot;);<br><br>const handleReducedMotion = () =&gt; {<br>  if(motionQuery.matches) {<br>    behavior = &quot;smooth&quot;<br>  }<br>}<br><br>motionQuery.addListener(handleReducedMotion);<br>handleReducedMotion();<br><br>button.addEventListener(&quot;click&quot;, e =&gt; {<br>  document.querySelector(&quot;&lt;some selector&gt;).scrollIntoView({ behavior });<br>});</pre><ul><li><em>“You must register </em>[…] <em>custom properties to make them animatable.”</em> I.e. use the @property syntax) ([1], p. 146)</li><li><a href="https://alistapart.com/article/designing-safer-web-animation-for-motion-sensitivity/#section7">Web animation expert Val Head’s characteristics of outstanding animations:</a> (1) An element’s path is made visible on the screen, so a user don’t have to keep track of it themselves, reducing congitive load. (2) They help decision making (3) They help build mental maps of spatial information (4) They help against change blindness (5) They help establish connections between objects. ([1], p. 147–148)</li><li>Common triggers of motion sensitivity that you should be carefult with are: (1) Animations that moves an object a large distance over the screen (including large scaling) (2) Mismatched direction and speed, often seen in parallax scrolling (3) Fixed background images ([1], p. 148)</li><li>Facundo Corradini is a developer who suddenly suffered a bad cause of vertigo, so a temporary disability can happen to anyone. ([1], p. 148)</li><li><em>“Avoid auto playing animations or videos, at least allow pauses to pause and stop them.” </em>([1], p. 149)</li></ul><h4>About Managing Focus</h4><ul><li>It is recommended to provide your own rules for the focus state, e.g. a thicker outline-width and increased outline-offset, since the default styles for focus often lack enough color contrast. ([1], p. 156)</li><li>outline works well for focus styles because it are well supported and don’t interfere with the layout, but you are not limited to using outline for focus styles. background-color and box-sahdow however might not be visible in forced-color mode. A workaround is to comine properties that are not visible in forced-color mode with a transparent outline, since forced color modes do interpret a transparent outline (E.g. outline: 0.5em solid transparent) ([1], p. 156–157)</li><li>Keyboard users should be able to perform the same actions that a mouse user can. Use correct semantic HTML to achive this for interactive content. ([1], p. 158)</li><li>Here is how to build an accessible tabs component ⬇️: ([1, p. 161])</li></ul><pre>&lt;div class=&quot;tabs&quot;&gt;<br>  &lt;h3 id=&quot;tabslist-heading&quot;&gt;Some title&lt;/h3&gt;<br>  &lt;div role=&quot;tablist&quot; aria-labelledby=&quot;tabslist-heading&quot;&gt;<br>    &lt;button id=&quot;tab-1&quot; type=&quot;button&quot; role=&quot;tab&quot; aria-selected=&quot;true&quot;<br>      aria-controls=&quot;tabpanel-1&quot;<br>     &gt;<br>        Tab 1<br>    &lt;/button&gt;  <br>    &lt;button id=&quot;tab-1&quot; type=&quot;button&quot; role=&quot;tab&quot; aria-selected=&quot;false&quot;<br>      aria-controls=&quot;tabpanel-2&quot; tabindex=&quot;-1&quot;<br>    &gt;<br>        Tab 2<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br><br>  &lt;div id=&quot;tabpanel-1&quot; role=&quot;tabpanel&quot; tabindex=&quot;0&quot; aria-labelledby=&quot;tab-1&quot;&gt;<br>    Tabpanel 1 content...<br>  &lt;/div&gt;<br>  &lt;div id=&quot;tabpanel-2&quot; role=&quot;tabpanel&quot; tabindex=&quot;0&quot; aria-labelledby=&quot;tab-3&quot;<br>    class=&quot;is-hidden&quot;<br>  &gt;<br>    Tabpanel 1 content...<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><ul><li>Use tabindex=&quot;-1&quot; when you want either: a) an HTML element that is not natively focusable to be focusable using Javascript ( element.focus()) and not keyboard-accessible, or b) to remove a natively keyboard-accessible HTML element from the tab order, but keep it focusable, e.g. the non-selected tab in the code example above, because pressing Tab should rather jump to the selected tabpanel, but with tabindex=&quot;-1&quot; , the non-selected Tab is focusable using the arrow keys ([1], p. 161)</li><li>tabindex=&quot;0&quot; makes nonfocusable elements keyboard-accessible, likt the tabpanel in the code example above ([1], p. 162)</li><li>Remember last focused element by storing it in a variable lastFocusedElement = document.activeElement ([1], p. 165)</li><li>The native dialog element is handy because it has an implicit dialog role, provides methods for opening an closing, makes the rest of the page inert and manages focus. ([1], p. 166)</li><li><a href="https://html.spec.whatwg.org/#dialog-focusing-steps">WHATWG’s (Web Hypertext Application Technology Working Group) dialog focus management steps</a> specifies the following: 1) If a focusable descendant exists, focus it 2) If not, focus the dialog element itself 3) If an element (including the dialog) has the autofocus attribute, use that instead ([1], p. 166)</li><li><a href="https://css-tricks.com/focus-management-and-inert/">According to Eric Bailey (an inclusive-design advocate) “99% of the time, you want to leave focus order alone”</a>. That means let the natural order decide, and only programmatically manage focus when it takes a lot of effort for the user to reach some part of the UI. <a href="https://html.spec.whatwg.org/#the-autofocus-attribute">That includes being carefult with the </a><a href="https://html.spec.whatwg.org/#the-autofocus-attribute">autofocus attribute</a>. ([1], p. 166)</li><li>The inert attribute makes the rest of the page inactive (all descendents become inactive). It makes it easy to ensure users don’t get lost elsewehere on the page, but make sure to test with users if that is the right choice for your specific cases. ([1], p. 177)</li><li>Keep the order of elements in the DOM and the visual order the same because keyboard users elsewise will have a hard time predicting where the focus goes next, users that have zoomed in may have to move around a lot and a blind user getting help from a sighted user might be confused. ([1], p. 174)</li><li>Add a skip link as the first element in the &lt;header&gt; element so keyboard users don’t have to click through the same elements repeatedly to come to the main content they probably want to interact with (e.g. to come to &lt;main&gt; instead of having to click through the &lt;nav&gt; element that they probably already are familiar with). You can also add skiplinks within your page if you have many interactive elements, like e.g. to skip a section that would require a lot of keyboard action to get past (like an interactive map or the navigation). Also, make sure that the element you skip to exists and not visually hidden — a lot of pages have broken skip links today. The whole poing of a skip link is to help keyboard users become more efficient — let that guide your decisions regarding skip links. ([1], p. 175-179)</li></ul><h4>About Navigating Sites</h4><ul><li>Most importantly, create a main navigation, preferably using the &lt;nav&gt; element to make it a landmark element that quickly can be accessed ([1], p. 182, 195)</li><li>Apply to the programming design principle <a href="https://en.wikipedia.org/wiki/Rule_of_least_power">“Rule of Least Power”</a>, you should choose the least powerful language suitable for a given purpose. In frontend development, this means starting with HTML and adding layers (CSS, JavaScript), only as needed. When creating a main navigation, keep things as simple as possible for your need. ([1, p.183])</li><li>Navigation links needs to meet <a href="https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html">the minimum WCAG 2.2 target size</a>, i.e. be at least 24 x 24 px, so increase the font-size and padding so that this criteria is met. ([1], p. 60, 183)</li><li><a href="https://youtu.be/zJLQdMmYWFQ?si=lMWQQrNkJXM0CSxX">The number of menu items should reflect the breath of your content, and the labels should be accurate, in order for users to be able to prioritize correctly, according to research by the Nielsen Norman Group (NN/g)</a>. The number of navigation items does not need to be limited by <a href="https://psychclassics.yorku.ca/Miller/">“The Magical Number Seven, Plus or Minus Two: Some Limits on our Capacity for Processing Information” (a paper from</a> 1956) because the users does not have to remember the navigation links in their short-time memory ([1], p. 184)</li><li>Artistic freedom on a web page is welcome, but some elements should follow conventions, and the main navigation is one of them — place it on the top of the screen, or for left-to-right languages, on the left edge. ([1], p. 185)</li><li>Highlight the current page in the navigation. This means aria-current=&quot;page” on the active navigation item, and the styling should convey it too (just remember not to rely on color alone, see previous bullet points for reasoning). ([1], p. 185–187)</li><li>box-shadow is often easier to work with than border since it does not take width or height of the element and it can provide nested borders, but it does not work well in forced-color mode unfortuneately (e.g. in Windows it may not show in a dark high contrast theme). ([1, p. 188])</li><li>Announce the number of items in the navigation so that this information is effectivly available also to a non-sighted user. This is done using the &lt;ul&gt; element, and it will also tell the user which item the user is currently visiting. Remember to also add the role=”list&quot; attribute because if default bullet point styling is removed by list-style: none or display: flex, some screen readers may not announce the element as a list at all without the role attribute set explicitly. We use the &lt;ul&gt; tag instead of &lt;ol&gt; because their order is not important to a user with a specific goal in mind. ([1], p. 189–192)</li><li>Hide the navigation on narrow viewports if it reaches a certain size of number of items. Users should be able to toggle its visibility and it should be hidden in a sidebar. The book gives a thorough recommendation on how to implement it using HTML, CSS and JavaScript only to add functionality and UI elements when Javascript is available (as a progressive enhancement). Here are the recommended steps ⬇️: ([1, p. 197–209].</li></ul><ol><li>Position the &lt;nav&gt; element fixed on narrow viewports and static for for wider using a media query.</li><li>Use a custom property — —nav-list-layout to toggle between flex-direction: column and row.</li><li>On narrow viewports, style it so it looks like a sidebar with e.g. a max width, background-color and a box-shadow.</li><li>Hide the list (and not the entire &lt;nav element to avoid hiding an important landmark element) on narrow viewports. Use visibility: hidden or display: none instead of opacity: 0 or translate-ing it away, because the latter two would leave the navigation still reachable by keyboard navigation.</li><li>Toggle the visibility of a list using a &lt;button&gt;. Wrap it in a &lt;template&gt; element so it does not need to be created in entity in JavaScript. Use JavaScript to add an event listener to it that toggles the aria-expanded attribute (and optionally, closes the navigation and puts focus back on the button when user clicks Esc). Insert the cloned button template before the &lt;nav&gt; element.</li><li>Use CSS to toggle the visibility of the list depending on the button’s aria-expanded attribute value ⬇️ :</li></ol><pre>ul {<br>  visibility: var(--nav-list-visibility, hidden);<br>}<br><br>[aria-expanded=&quot;true&quot;] + ul {<br>  --nav-list-visibility: visible;<br>}<br><br>@media (min-width: 48em) {<br>  ul {<br>    --nav-list-visibility: visible;<br>  }<br>}</pre><ul><li>The “burger icon” is a common way to hide the navigation on narrow viewports. Such an icon should be combined with a visual label like “Menu”. The NN/g has done research on this: <em>“Discoverability is cut almost in half by hiding a website’s main navigation. Also, task time is longer and perceived task difficulty increases.”</em> ([1], p. 2017)</li><li>Users with vestibular disorders have a problem with their vestibular system, which is the mechanism in the inner ear that provides an internal sensor to our body’s physical position and orientation in the world. Pain can be triggered by animations in these users, and the prefers-reduced-motion preferance can be queried in JavaScript also. Consider adding animation: none !important and transition: none !important on all elements if this preference is set to reduce. Not all animations are equally troublesome, some help with decision making, signify relationships between objects, or reduce cognitive load by making the path of elements visible, but generally avoid animations like parallax effect, elements at different speeds, spinning effects etc. that are often mostly for aesthetic purposes for users that has set prefers-reduced-motion: reduce. It is the size of the motion relative to the space available on the screen that matters. ([1], p. 209–213)</li><li>Add a simple fade in and out animation to the navigation by transitioning opacity and visibility (e.g. transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out) and if the user has (prefers-reduced-motion: no-preference), a sliding animation (transition: transform 0.6s cubic-bezier(.68,-.55,.27,1.55), visibility 0.3s ease-in-out) and translating it off 100% from the start can be added. ([1], p. 209–211)</li><li>Add submenus by nesting &lt;ul&gt; elements and hide them when the number of menu items grows too large. Hide them using CSS and add a &lt;button&gt; with an appropriate icon to signify it can be clicked for a submenu ⬇️. Or you can move the main link within the submenu to avoid the label and the submenu button next to it doing two different actions. Consider making the submenu show on hover, but avoid it on focus since it can be frustrating for keyboard users to have it open automatically. ([1], p. 215–218)</li></ul><pre>&lt;li&gt;<br>  &lt;a id=&quot;top-nav-item-1&quot; ...&quot; ..&gt;<br>  &lt;button type=&quot;button&quot; aria-expanded=&quot;false&quot; aria-lebelledby=&quot;top-nav-item-1&quot;    <br>    aria-controls=&quot;top-nav-item-1-sub&quot;  <br>  &gt;<br>    &lt;span aria-hidden=&quot;true&quot;&gt;&amp;#9207;&lt;/span&gt; <br>  &lt;/button&gt;<br><br>  &lt;ul id=&quot;top-nav-item-1-sub&quot;&gt; <br>    ...<br>  &lt;/ul&gt;<br>&lt;/li&gt;<br></pre><ul><li>“Unless you are building something very close to a desktop application, avoid menu roles in navigations” ([1], p. 222)</li></ul><h4>About Toggling Content Visibility</h4><ul><li>It is usually better to show content, but designers often opt for tabs, accordions, fly-out navigations etc. to fit as much information as possible in a limited space. ([1], p. 223)</li><li>See the 6 ways to hide content in the list below ⬇️. “Available” refers to if keyboard users should still be able to access the content you want to hide (i.e. if it should be semantically hidden or not). <a href="https://kittygiraudel.com/2021/02/17/hiding-content-responsibly/">Kitty Giraudel has a grear post on how to hide content responsibly</a>. ([1], p. 226)</li></ul><ol><li><strong>Visually hidden</strong>: .sr-only CSS class. Visible: No. Available: Yes</li><li><strong>Visually hidden: </strong>opacity: 0. Visible: No, but space remains. Available: Depends, i.e. remember to hide is semantically as well if needed.</li><li><strong>Visually hidden: </strong>transform: scale(0). Visible: No, but space remains. Available: Yes, so remember to hide is semantically aswell if needed.</li><li><strong>Semantically hidden</strong>: aria-hidden=&quot;true&quot;(or alt=&quot;&quot;` on &lt;img&gt;). Visible: Yes. Available: No</li><li><strong>Visually and semantically hidden: </strong>display:none. Visible: No. Available: No</li><li><strong>Visually and semantically hidden: </strong>visibility: hidden.Visible: No, but space remains. Available: No</li></ol><ul><li>Rules to abide by when hiding elements to avoid messing it up ⬇️: ([1], p. 227)</li></ul><ol><li>Only hide content when you are not able to adapt the content or the design.</li><li>Don’t use aria-hidden=&quot;true&quot; or role=&quot;presentation&quot; on focusable elements (<a href="https://www.w3.org/TR/using-aria/#4thrule">the “Fourth Rule of ARIA Use” by the World Wide Web Consortium [W3C] group, the main standardization organization for the web</a>).</li><li>When you use CSS properties to hide elements visually, like opacity, height, transform, combine it with a property to hide it also semantically (like visibility: hidden).</li><li>Don’t hide elements that are references elsewhere in the document semantically.</li></ol><ul><li>The &lt;details&gt; element has a lot of benefits (e.g. works without JavaScript), but the problem is that there are a lot of inconsistencies between browsers and screen readers. If you should rather create a custom solution depends on the experience you want to give your users, and the books provides the recommended solution if you need to implement you own disclosure widget. ([1], p. 229–231)</li><li>You can create groups of disclosure widgets (an accordion), and you can nest them, on a page with a lot of information to limit the cognitive load on users and they can themselves choose what information to see using JavaScript as a progressive enhancement. E.g. a FAQ-page where users can hide &amp; show the answers. This is done by e.g. creating &lt;h3&gt;s with a following &lt;div&gt; that has an aria-labelledby pointing to the title, and use JavaScript to loop through all &lt;h3&gt;s to replace it with a button, set the aria-expanded and aria-controls attributes and add a click event to toggle it. <a href="https://www.w3.org/WAI/ARIA/apg/patterns/accordion/">Read the ARIA Authoring Practices guide on accordions by the W3C group</a>. E.g. you can add keyboard support for up and down keys. <a href="https://www.smashingmagazine.com/2017/06/designing-perfect-accordion-checklist/">Smashing Magazine’s Vitaly Friedman has an article called “Designing The Perfect Accordion”</a>([1, p. 234–238])</li></ul><h4>About Constructing Forms</h4><ul><li>One of the <a href="https://inclusivedesignprinciples.info/">Inclusive Design Principles</a> (defined by Heydon Pickering, Léonie Watson, Henny Swan and Ian Pouncey) is to be <strong>consistent</strong>: <em>”Instead of developing new form-design patterns, stick to what already exists. Provide users with familiar patterns instead of forcing them to learn new ones.”</em> )</li><li>The <a href="https://frankchimero.com/blog/2015/the-webs-grain/">common patterns that emerge that you should adhere to in order to stay consistent with the web &amp; other web sites, are the best patterns, according to Frank Chimero:</a> <em>“Many sites will share design solutions, because we’re using the same materials. The consistencies establish best practices; they are proof of design patterns that play off the needs of a common medium, and not evidence of a visual monoculture.” </em>([1], p. 243)</li><li>You should pick a simple solution that users most likely know from other websites when creating forms, in order to not increase the cognitive load on the users that is already performing a task that requires effort (filling out a form). ([1], p. 243)</li><li>E.g. <a href="https://axesslab.com/toggles-suck/">use a checkboc instead of a toggle switch if possible in a form, because the state of a toggle switch is not always intuitive, according to Joel Holmberg</a>. For example, it can be difficult to understand if a toggle switch with the text ON and the color green in the background indicates a state or an action.</li><li>Keep the rectangular shape of text input fields and don’t make it look special. Don’t remove the borders since it removes its signifiers (which is a design aspect that suggests how an object should be used). ([1], p. 244)</li><li>The <a href="https://www.gov.uk/service-manual/design/form-structure">UK Governmental design manual for structuring forms</a> advises one should gather all the questions you want answered by the user <em>before</em> you create the form to make sure you don’t ask unnecessary questions you can’t derive elsewise. For each questions you should be able to answer: 1) Why you need this information 2) What you will do with it 3) Which users need to give tyou this information 4) How you will check the information is accurate 5) How you will keep the information up-to-date and secure ([1], p. 245)</li><li><em>“… every time you cut a field </em>[…] <em>from a form, you increase the form’s conversion rate.” </em>([1], p. 245)</li><li>The right input field might not make a difference on desktop, but on mobile, it affects the keyboard layout, making it easier to type for the user. ([1], p. 245)</li><li>For single-choice questions, use radio buttons (and not &lt;select&gt;, because it hides choices by default, unless users will benefit from being able to start typing to select). ([1], p. 245)</li><li>There are a lot of advice to give about creating web forms, but some of them related to the aim of informing the users and giving them control are: 1) Allow users to go back &amp; forth between steps and tell them what will happen when they navigate to the next step 2) Describe fields, especially if they cause a change of context 3) Allow users to correct mistakes 4) Summarize the entered data before submission ([1], p. 247)</li><li>You can create a reference using aria-labelledby , e.g. to a button element stating the action like “Search”, if the &lt;input&gt; field does not have a visible label. ([1], p. 248)</li><li><em>“… label all form elements.” </em>([1], p. 249)</li><li>Labels above works best for form controls, and horizontal placement best for radio buttons and checkboxes. ([1], p. 250)</li><li>Avoid using just a placeholder value inside a input field instead of a label (the also includes the floating label solution where the placeholder shrinks and moves to the upper left corner when the user starts to type).([1], p. 251)</li><li><a href="https://www.gov.uk/service-manual/design/designing-good-questions">The UK government has a manual “Designing good questions”</a> that explains how and when to provide help text for e.g. legal jargon, what format information should be given, where to find obscure information, what happens with the personal information and the consequence of making one choice over another. ([1], p. 253)</li><li>Additional information about the form can be placed: 1) As overall instructions before the form, e.g. as a list 2) Short inline description of e.g. the format of the data can be provided inline in the label, like like “Birthday (dd.mm.yyy)” 3) Longer instructions can be put after the label using e.g. the &lt;p&gt; element, and let the &lt;input&gt; element point to it using aria-describedby (it is Adama Silver that suggests in his book “Form Design Patterns” that it is wise to put the form hints between the label and the input field, and not after the input field) ([1], p. 253)</li><li>The placeholder attribute is unsuitable for providing important help text and hints because of the following reasons: 1) It disappears when the user starts to type, so if it says anything important, the users has to remember it, increasing the needed mental effort 2) Browser’s autofill feature might prepopulate it, meaning users might never see the placeholder text, or remove the prepopulated text to read the placeholder text 3) The placeholder text is often gray by default, and thus not provide sufficent WCAG constrast 4) Long placeholder text might be cut off 5) <a href="https://www.nngroup.com/articles/form-design-placeholders/">Users may mistake placeholder text for a value, which NN/g confirmed is more prevalent in users with cognitive disabilities</a>. ([1], p. 251, 253)</li><li>Disabled users are most likely to make errors in a form, and thus the error reporting needs to be as accessible as possible. ([1], p. 256)</li><li>General rules for error messages: 1) Don’t rely on color alone (e.g. use an icon too) 2) Inform users that something went wrong 3) Write clear and meaningful error messages 4) Provide instructions on how to fix the error 5) Allow users to access erroneous fields 6) Allow users to (re)submit the form ([1], p. 257)</li><li>If there is only one error in the form: Put focus on it, add aria-invalid=&quot;true&quot; and aria-describedby=&quot;&lt;error-message-element-id&gt;&quot; to the erroneous &lt;input&gt; field, in addition to adding the error message element (e.g. as a &lt;div&gt;) right after the the erroneous &lt;input&gt; field. ([1], p. 255, 257)</li><li>If there are multiple errors: 1) When using server-side rendering: You can list all the errors before the form, see code example below ⬇️. You can also update the title element to include the number of errors, e.g. &lt;title&gt;2 errors - Sign up - Johanna’s Toy Store&lt;/title&gt; 2) When using client-side rendering: Do the same or use a live region to inform users about the errors when they try to submit the form. ([1], p. 256-258)</li></ul><pre>&lt;div region=&quot;role&quot; aria-labelledby=&quot;error_heading&quot; tabindex=&quot;0&quot;&gt;<br>  &lt;h2 id=&quot;error_heading&quot;&gt;2 issues found&lt;/h2&gt;<br><br>  &lt;ul&gt;<br>    &lt;li&gt;<br>      &lt;a href=&quot;#email&quot;&gt;Please enter a valid e-mail address&lt;/a&gt;<br>    &lt;/li&gt;<br>    &lt;li&gt;<br>      &lt;a href=&quot;#password&quot;&gt;Password must contain at least one number&lt;/a&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;div&gt;</pre><ul><li><a href="https://cloudfour.com/thinks/progressively-enhanced-form-validation-part-1-html-and-css/">Gerardo Rodriguez writes you can use the native form API for validation, but provide your own markup and styling, because there are several downsides to using native form validation</a>, and some of them are: 1) The styling of the error messages vannot be customized 2) Some form controls cannot be validated 3) The error messages might not be vlear or helpful 4) The error messages don’t always resize when zooming 5) Error messages are not always linked correctly to the corresponding field. ([1], p. 258)</li><li>When providing your own form validation, you should adhere to Postel’s Law: <em>“… you should be conservative in what you send, but be liberal in what you accept.” </em>I.e. you should allow trivial mistakes and write code that corrects them, because it takes e.g. one line of code to strip chars that are not a number when the user has typed a phone number, but many more lines to write an error message informing about the mistake. ([1], p. 259)</li><li>Here are some tips from Adam Silver from his book “Form Design Patterns” on how to write a good error message: 1) Be concise, but don’t omit words at the cost of clarity 2) Be consistent by using the same tone and punctuation throughout 3) Avoid pleasantries like “Please” because they imply choice 4) Don’t be generic, be specific. E.g. instead of writing “There is an error”, explain what went wrong 5) Use plain natural language, i.e. avoid jargon like “invalid”, “forbidden” or mandatory” 6) Use the active voice, e.g. “Enter your name” 7) Let users know what has gone wrong and how to fix it, but don’t blame them. E.g. rather write “Enter your name” instead of “You did not enter a name” ([1], p. 258)</li><li>If you form includes group of fields of the same type that belong to different questions, wrap them inside the &lt;fieldset&gt; element together with a &lt;legend&gt;element. It is <em>always </em>a good idea for radio buttons (e.g. yes &amp; no for a question) or checkboxes. It is only neccessart when a <em>higher label label</em> is needed. Avoid nesting &lt;fieldset&gt;elements because it van give weird screen reader behavior. Always include a &lt;legend&gt; element. ([1], p. 259, 261)</li><li><a href="https://www.w3.org/WAI/tutorials/forms/multi-page/">Split long forms into multiple smaller forms in steps (recommended by the Web Accessibility Initiative [WAI])</a> to make it less daunting to fill out (especially for people with cognitive disabilities), and let it be possible to save at each step so a user can continue later. <a href="https://www.gov.uk/service-manual/design/form-structure#start-with-one-thing-per-page">The UK Governmental service manual even recommends asking only one question per page</a>. That has the benefit of allowing users to focus on one task at a time, and it is easy to give and fix form errors. Repeat overall instructions for filling out the form in each steps. ([1], p. 262–264)</li><li>Always inform users in the first step how many steps the form has, how much they have completed, and what remains. A good progress indicator can be hard to design, especially on mobile where the space is limited. Most easily, you can use the &lt;title&gt; element (e.g. &lt;title&gt;Step 2 of 4: Payment - Checkout - Johanna’s Toy store&lt;/title&gt;) or the &lt;h1&gt; element (e.g. “Payment (Step 2 of 4)”). Alternatively, use a list and use aria-current to highlight the current step. ([1], p. 263–264)</li><li>Forms summarized: 1) Only ask a questions if you need to 2) Pick the right element for the task 3) Identify each element by labelling it accurately ([1], p. 252)</li></ul><h4>About Filtering Data</h4><ul><li>Add only a filtering form if you need it (i.e. the number of results is vast). Allow users to select only one value for a filter if the number of values is big using the &lt;select&gt; element (e.g. selecting an artist in a music database. Use checkboxes if the filter has fewer values (e.g. only five options. Use a radio button if a filter can have only one item at a time (e.g. an shipping option). ([1], p. 269)</li><li>In server-side-rendering, the feedback when submitting a filtering form is handled (the page reload). In client-side rendering, you can’t rely on just the visual feedback because a user might be blind or use a high zoom. Thus, choose one of two approaches, or combine them if user testing shows that is best for your use case: 1) After filtering and repopulating the results section, move focus using JavaScript using .focus() to the result region (which is a landmark for easy navigation, e.g. &lt;div role=&quot;region&quot; tabindex=&quot;-1&quot;&gt;) 2) Keep the focus on the submit button, but update the live region element inside the search result region that should be included in either case (e.g. &lt;div role=&quot;status&quot;&gt;Showing 40 of 40 results&lt;/div&gt;) ([1], p. 274)</li><li>Use pagination only if you need it. Implement it as a &lt;nav&gt; element with a &lt;ol&gt; inside, and as &lt;a&gt; elements inside each list item. Make sure to add aria-current=&quot;page&quot; to the selected page. A number inside each link is sufficient, but you can add e.g. aria-label=&quot;Page 1&quot; to be more explicit. ([1], p. 277)</li><li>When sorting data, always inform the user about what is selected and about changes. For &lt;select&gt; elements, use the selected attribute. For radio buttons and check boxes, use the checked attribute. For toggle buttons use aria-pressed=&quot;true | false&quot;. For the changes, update a live region element to inform screen readers. ([1], p. 274)</li><li>If a form has a lot of attributes it can filter on, considering collapsing or just showing the first few with an option to expand if needed. E.g. use a disclosure widget by wrapping the text content of a &lt;legend&gt; in a &lt;button&gt;, set the aria-expanded=”true&quot; attribute on the &lt;button&gt; on click, and let the fieldset’s div&gt; that contains the &lt;input&gt; elements get display:block if fieldset:has([aria-expanded=&quot;true&quot;]). ([1], p. 281-282)</li></ul><h4>About Presenting Tabular Data</h4><ul><li>&lt;table&gt; has been misued a lot in the past (for layout), but use it when you need to present data with more than one dimension. Use it if : 1) Comparing the data is a neccessary and 2) The columns can have meaningful labels ([1], p. 285–286)</li><li>The &lt;table&gt; element provide users with screen readers with helpful keyboard shortcuts (e.g. navigating between the cells using screen reader navigation keys, announcing column and row headers along the way). ([1], p. 287)</li><li>Make sure a &lt;table&gt; is usable on smaller viewports too and don’t cause overflows. This can be done by adding a wrapping a scrollable (overflow:auto) &lt;div&gt; around the &lt;table&gt; element, with a tabindex=&quot;0&quot; (to make it focusable), aria-labelledby to the &lt;table&gt;&#39;s caption and role=&quot;region&quot; (since you can not label a generic element).([1], p. 291–292)</li><li>When adding sort to a table column, remember: 1) Use a &lt;button&gt; element inside the &lt;th&gt; element 2) Set aria-sort=&quot;ascending&quot; | &quot;descending&quot; on the &lt;th&gt; element when sorted 3) Provide visual and screen reader feedback — e.g. an arrow beside the column name in the right direction (just add a triangle using &lt;path&gt; inside a &lt;svg&gt; that gets currentColor given it’s parent has a corresponding aria-sort value) and let a live region announce it, like ⬇️: ([1], p. 296-300)</li></ul><pre>const updateLiveRegion(text) {<br>  const liveRegion = document.querySelector(&quot;[role=&#39;status&#39;]&quot;)<br>  liveRegion.textContent = text; // E.g. &quot;Sorted ascending&quot;<br>  <br>  // Need to clear it, if not the screen reader keeps announcing it<br>  // Unfortuneately, we have no way of knowing exactly how long it will<br>  // take to read the text, so the time needs to be a good enough guess :/<br>  setTimeout(() =&gt; {<br>    liveRegion.textContent = &quot;&quot;;<br>  }, 1000)<br>}</pre><h4>About Creating Custom Elements</h4><ul><li>The author thinks web components was made with a11y in mind, so when using it, <em>we </em>as developers have to have an a11y-first mindset. ([1], p. 301, 318)</li><li>Referencing an element from light DOM in shadow DOM or vice versa breaks. This applies to both ids and ARIA attributes. (Although the ElementInternal API solves this partly by allowing a custom element with the property formsAssociated=true to be associated with a form, and this.internals = this.attachInternals gives access to e.g. labels). ([1], p. 301, 304–305)</li><li>ARIA Mixins (only supported by Safari and Chrome Canary, as of the writing of the book) and the two proposals “cross-root ARIA delegation” and “cross root ARIA reflection” would help this problem. It is considered a problem that needs to be solved, because to a user, the relationship between the light and the shadow DOM is visually evident, so it is problematic that it can’t be expressed in code. For this reason. experts advise being careful about using the shadow DOM. ([1], p. 307–309).</li><li>There are two possible ways to focus a custom element in the shadow DOM: 1) If the mode is &quot;open&quot;: Accessing the .shadowRoot property (e.g. document-querySelector(&quot;my-element&quot;).shadowRoot.querySelector(“button&quot;).focus()) 2) Pass in delegatesFocus option to the shadow DOM — then calling focus() on the element will reach the first focusable element in the shadow DOM.([1], p. 311–312)</li><li>If you test a11y manually, remember to rather use document.activeElement.shadowRoot.activeEleemnt to return the actual focused element inside the shadow root of a component. ([1], p. 313)</li><li>For automated testing, know that not all test tools support shadow DOM. The book has a code snippet you can use to test your tool, and it shows that all automatic a11y testing tools the author tested (including axe/Lighthouse and WAVE) did not adequately report all a11y violations. ([1], p. 313–315)</li><li>Custom elements are inherently progressive enhancements, since they render their slotted content even if JavaScript is disabled. ([1], p. 316–317,319)</li><li>You can bake a11y into you custom elements, making it safers for developers to use if they e.g. are a part of a design system. If something mandatory is missing, you can rather have the whole component render an error instead. ([1], p. 315, 318)</li></ul><h4>About Debugging Barriers</h4><ul><li>Examples of automated a11y testing tools are: axe DevTools, Google Lighthouse, WAVE, ARC Toolkit and IBM Equal Access Accessibility Checker and pa11y. ([1], p. 322–327)</li><li>Automated testing is the first step before you proceed to manual testing, but it won’t catch all bugs. ([1], p. 328)</li><li>Use the a11y tree in DevTools to debug a11y issues. ([1], p. 328)</li><li>The tooltip functionality when hovering an element using DevTools shows a11y information. ([1], p. 334)</li></ul><h4>Sources</h4><p>[1] Manuel Matuzovic: Web Accessibility Cookbook<em>, </em>book, 2024, O’Reilly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34cb22cb742" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Review: Is Martin Fowler’s “Refactoring” still relevant?]]></title>
            <link>https://forsethingvild.medium.com/book-review-is-martin-fowlers-refactoring-still-relevant-d724c146f774?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d724c146f774</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[martin-fowler]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 09:02:20 GMT</pubDate>
            <atom:updated>2026-04-10T07:26:42.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The book cover of Martin Fowler’s book “Refactoring — Improving the Design of Existing Code”, second edition." src="https://cdn-images-1.medium.com/max/1024/1*a7VOLd_YLjInyUr1WwwfSg.png" /><figcaption>Book cover image from <a href="https://www.oreilly.com/library/view/refactoring-improving-the/9780134757681/">here</a>.</figcaption></figure><p>I recently read Martin Fowler’s book <a href="https://martinfowler.com/articles/refactoring-2nd-ed.html">“Refactoring – Improving the Design of Existing Code” (second edition)</a>. This article tries to summarize the most important things I learned and also answer the question – is the book still relevant in 2025, 26 years after the first edition was released in 1999?</p><p>The article starts with the contents of chapter 1–4, which I found the most value in. Probably because they outline the principles for <em>why</em> we do the activities of refactoring and testing our code — which has not become outdated like perhaps some of the later mentioned refactoring methods. A list of the refactoring methods is provided at the end, but the book itself naturally needs to be read to be able to understand and apply the refactorings.</p><p><em>Disclaimer</em>: This article is mainly an attempt to enforce my own learning by making notes as I go.</p><h3>Standing on the Shoulders of Giants</h3><p>As the book acknowledges, I too have to point out that books like these seem to have laid the foundation for the programming as we know it today. The book underlines that it did not coin the term “refactoring” when its first edition was released, but it tries to explain the birth of the term.</p><p>Evidently, some of the first people in the industry that recognized the importance of it, was Ward Cunningham and Kent Beck (co-author) in the 1980s. Kent Beck later developed the Extreme <a href="https://en.wikipedia.org/wiki/Extreme_programming">Programming methodology</a>, one of the first agile software methods [1, p. 63]. (He also created the <a href="https://en.wikipedia.org/wiki/JUnit">Java JUnit testing framework</a> [1, p. 86] and coined the term “Test Driven Development” [1, p. 87] 🤯!)</p><p>It was Kent Beck himself that inspired Martin Fowler, as he worked with him and saw the difference it made refactoring the way Beck did it. Due to the lack of a books on the subject that could help explain the technique, Fowler decided to write one himself. The term “refactoring” caught on in the industry, and and the rest is history.</p><p>It seems obvious that this book plays an important part in the history of programming. As a developer born in the 1990s (I was five years old when the first edition came out), you often hear senior developers explain how something in programming today is so much easier that it was before. But, without having the firsthand experience of how it was before, it can be hard to relate.</p><p>I wanted to read this book as an attempt to maybe catch more of the references to the “old days”, and also to evaluate if this book is worth a read as a developer in the 2020s.</p><h3>The Structure of the Book</h3><p>The book starts with chapter one showing an example of a refactoring of a small program, using the methods we will later learn. Chapter two explains general principles about refactoring and explains <em>why</em> we want to do it. Chapter three outlines what us typically bad code (code smells), and chapter four describes how to test code – a crucial step for making refactoring effective. The rest of the book (chapter 5–12) are the different methods used when refactoring (61 in total).</p><h3>Important Quotes from Chapter One</h3><p>These are the quotes from chapter one I want to take with me:</p><blockquote>“When you have to add a feature to a program but the code is not structured in a convenient way, first refactor the program to make it easy to add the program, then add the feature” <em>[1, p. 4].</em></blockquote><blockquote>“Before you start refactoring, make sure you have a solid suite of test.” <em>[1, p. 5].</em></blockquote><blockquote>“… programmers love to argue about what good code looks like … I believe, however, that we can go beyond taste and say that the true test of good code is how easy it is to change it. Code should be obvious: When someone needs to make a change, they should be able to find the code to be changed easily and to make the change quickly without introducing any errors.”<em> [1, p. 43].</em></blockquote><blockquote>“A healthy code base maximizes our productivity, allowing us to build more features for our users both faster and more cheaply. To keep code healthy, pay attention to what is getting between the programming team and that ideal, then refactor to get closer to the ideal.” [<em>1, p. 43].</em></blockquote><blockquote>“… people … are surprised by how small my steps are, each leaving the code in a working state that compiles and passes its tests … The key to refactoring is recognizing that you go faster when you take tiny steps, the code is never broken, and you can compose those steps into substantial changes.” [<em>1, p. 44].</em></blockquote><h3>The Essence of Refactoring</h3><p>In chapter two, Fowler explains the concept of “two hats”. His meaning of this, is that he swaps consciously between two activities – either he is adding functionality, or he is refactoring. This means that if he realizes while he is adding a new feature that it would be easier to do so if the code was structured differently, he stops working on the feature and starts refactoring. During the refactor, he makes sure not to add functionality (not even tests, unless it is a missed case). This leads me over to the definition if the verb “refactoring” presented by the book:</p><blockquote>“Refactoring (verb): to restructure software by applying a series of refactorings without changing its observable behavior” <em>[1, p. 45]</em></blockquote><h3>Reasons for Refactoring</h3><p>These are the reasons Fowler outlines in chapter two to explain why we should refactor:</p><ul><li>It improves the design of software: <em>“As people change code to achieve short-term goals, often without a full comprehension of the architecture, the code looses its structure. Loss of the structure of code has a cumulative effect. The harder it is to see the design in the code, the harder it is for me to preserve it, and the more rapidly it decays. Regular refactoring helps keep the code in shape.” </em>[1, p. 47]</li><li>It makes software easier to understand</li><li>It helps you find bugs: Because you deepen your understanding of the code while you refactor it.</li><li>It helps you program faster: <em>“… some teams report a different experience. They find they can add new features faster because they can leverage the existing things by quickly building on what’s already there. The difference between these two</em> [writer’s note: first team reported that it was easy to add features at first, but as the code base has grown, it has become more difficult, see image below ⬇️] <em>is the internal quality of the software. Software with a good internal design allows me to easily find how and where I need to make changes to add a new feature”.</em> [1, p. 49]</li></ul><figure><img alt="Graphs from page 49 in Martin Fowlers book “Refactoring — Improving the Design of Existing Code”, second edition. The x-axis is time, and the y-axis is”cumulative functionality”. The blue graphs belongs to a team that does not perform refactoring, in which the cumulative functionality will not increase after some time due to poor design. The pink graph belongs to a team that successfully performs refactoring and thus can keep increasing the cumulative functionality." src="https://cdn-images-1.medium.com/max/1024/1*EdQCnj0aqo1PqI2O3hyUMg.jpeg" /><figcaption>A diagram from the book showing how refactoring can help increasing the cumulative functionality. The bottom-most graph belongs to a team that does not refactor, and thus the the cumulative functionality stalls due to poor design. The graph that keeps increasing belongs to a team that performs refactorings successfully, and thus preserves good design over time [1, p. 49].</figcaption></figure><h3>When to Refactor?</h3><p>I like this little rule from the book – three strikes (think baseball ⚾️), then you refactor. Meaning it takes some exposure to a problem before you have the will and understanding to do something about it. Fowler groups the opportunities we have to refactor in the following way:</p><ul><li>To make it easier to add a feature</li><li>To make code easier to understand</li><li>“Litter-pickup: Basically <a href="https://deviq.com/principles/boy-scout-rule">the Boy Scout rule</a>.</li><li>Planned: E.g. when the team has neglected refactoring for too long. Should generally try to be avoided, since one should always try to refactor regularly opportunistically. (One interesting discussion in this subchapter, is Fowler’s take on whether refactoring and new feature work should be in the same commits. His take is that they are often so interwoven, plus they provide context to each other, so it is usually not worth the time separating the two. However, each team needs to experiment with what works for them.)</li><li>Long-term: This is e.g. when you have to replace a library. Fowler writes he is reluctant to let the team work dedicated with this, but rather work on the problem over a few weeks as they regularly are near the code and improve it in the right direction. One can start this process by firstly just adding an abstraction layer that works as an interface to either library.</li><li>In a code review: Fowler has best experiences with this when the code review happens sitting one-on-one with the author, i.e. pair programming.</li></ul><p>When should you not refactor? Fowler adresses that you absolutely do <em>not</em> need to refactor something just because it looks ugly. If you can just treat it as an API and don’t need to add a new feature, it is fine. Refactoring is for when you need to deepen your understanding of something. Also, sometimes an entire rewrite might be appropriate instead, for instance if the code proves very difficult during a refactor.</p><p>Fowler also includes some paragraphs about what you should say to you manager about the refactorings. He points out that a manager with sufficient technical awareness, should know that refactoring is a necessity to continued productivity. If that is not the trait of the manager, simply not mentioning it is Fowlers controversial (his words) opinion. The reason is that it is simply a skill of a programmer to know that refactoring is the fastest and best way to do something – we are just doing our job.</p><h3>Refactoring and Performance</h3><p>One interesting aspect about refactoring Fowler discusses in chapter two, is how it affects performance. He writes that when he refactors, he does it without thinking about performance. That means even taking deliberate choices during the refactoring phase that perhaps would slow down the program. His argument is that a well-written program is easier to improve performance on later.</p><p>Thus, improving performance should be an activity later <em>separate </em>from the refactoring process. His best advice for enhancing performance, is by a “deliberate performance optimization exercise” [1, p. 66]. That means running the program with a profiler and finding the parts where the performance issues lie.</p><p>This is better than the alternative approach of “constant attention” to optimization [1, p. 65], i.e. that developers always pay attention and implement whatever they think will improve performance. He argues that this leads to optimization measures scattered all over the code, which makes the code harder to read, and it is unknown if they are even necessary.</p><h3>Code Smells</h3><p>Below is the list of code smells the book points out (that usually tells you that some refactoring most likely is necessary). I included a small explanation for those I don’t think have an obvious name.</p><ol><li>Mysterious Name</li><li>Duplicated Code</li><li>Long Function: <em>“… whenever we feel the need to comment something, we write a function instead”</em> [1, p. 73].</li><li>Long Parameter List</li><li>Global Data</li><li>Mutable Data</li><li>Divergent Change: When you want to make a functional change, but you have to change different parts (contexts) of the code to achieve it.</li><li>Shotgun Surgery: Happens when you want a functional change, but you need to make changes in a lot of different places.</li><li>Feature Envy: When a function in a module communicates more with functions in an other module than the functions within its own module.</li><li>Data Clumps: When fields or parameters often appear together, they should rather be made into e.g. an object.</li><li>Primitive Obsession</li><li>Repeated Switches: Because every time a new case appears, you need to update a lot of switches. Polymorphism might be a better option.</li><li>Loops: As the book later explains, “pipeline” functions are recommended instead, like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">.map</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">.filter</a> etc. in JavaScript, because they better show the elements included in the processing and what is done with them.</li><li>Lazy Elements: E.g. a class that over time has been downsized to only contains only one function — then it should be deleted.</li><li>Speculative Generality: E.g. when too much code has been added to handle future scenarios, but that currently does not happen.</li><li>Temporary Field: E.g. a field in a class that is only set in certain circumstances.</li><li>Message Chains: When several get-functions are called in order to compose an object.</li><li>Middle Man: E.g. when a class delegates too much to an other class.</li><li>Insider Trading: Modules that communicate too much together.</li><li>Large Class</li><li>Alternative Class with Different Interfaces: E.g. when two classes are <em>almost</em> the same.</li><li>Data Class: Classes only with fields (and their getter and setter methods).</li><li>Refused Bequest: If e.g. a subclasses don’t need the method or data of the parent, the hierarchy is wrong.</li><li>Comments: The book does not think comments are inherently bad, but argues that they are often used as a result of bad code. It recommends rather extracting the block of code in need of a comment to a function with an explanatory name. Comments can be needed to explain the <em>why</em>, or in cases in which <em>you don’t really know </em>what to do.</li></ol><h3>The Importance of Tests</h3><p>Chapter four is about how to build sufficient tests for refactoring. Here are the quotes from chapter four that I found the most helpful:</p><blockquote>“… I ran the tests frequently — which means only a few minutes had elapsed. I thus knew that the source of the bug was the code I had just written. As it was a small amount of code that was still fresh in my mind, the bug was easy to find.” <em>[1, p. 86]</em></blockquote><blockquote>“You should concentrate on where the risk is. Look at the code and see where it becomes complex. Look at a function and consider the likely areas of error. Your tests will not find every bug, but as you refactor, you will understands the program better and thus find more bugs. Although I always start refactoring with a test suite, I invariably add to it as I go. <em>[1, p. 99]</em></blockquote><blockquote>“Think of the boundary condition under which things might go wrong and concentrate your tests there” <em>[1, p. 97]</em></blockquote><blockquote>“Don’t let the fear that testing can’t catch all bugs stop you from writing tests that catch most bugs”. [1, p. 98]</blockquote><blockquote>When you get a bug report, start by writing a unit test that exposes the bug. [1, p. 99]</blockquote><blockquote>“If someone says their code was broken for a couple of days while they are refactoring, you can be pretty sure they were not refactoring.”<em> [1, p. 46]</em></blockquote><p>The pattern of his tests is usually this: <strong>Set up</strong> (a fixture, i.e. det data you will run the test on), <strong>exercise</strong> (i.e. run the function you want to test on the data), <strong>verify</strong>. This is equivalent to other phrases you may have heard, like “given-when-then”, or “arrange-act-assert”.</p><p>Chapter four contains more general tips on testing, but I considered a lot of them so well-known today that I did not bother including them here (e.g. that tests should be “self-checking” and not just print out a result you have to check for yourself😅).</p><h3>The Refactoring Methods</h3><p>Chapter 6–12 are the actual refactoring methods. The book recommends however, to read through this catalog roughly to know what is in it. The details are not important, because it is when you actually need to do a refactoring, that you will rather look it up.</p><p>Each refactoring is presented with: a name, a short visual sketch to help aid memory, the motivation behind it, the mechanics (a list of steps on how to perform it), and examples of how it is performed.</p><p>At the end of this article follows a list of the names of all the refactoring methods. The they don’t make sense necessarily in their name alone, but I think nevertheless they give a nice impression of what the book is about, so I included the list for the most interested readers.</p><h3>Selected Quotes from the Refactorings</h3><p>Again, there are some quotes from the book that I will try to with me, also when it comes to the specific refactorings:</p><p>About Extract Function:</p><blockquote>“If you have to spend effort looking at a fragment code and figuring <em>what</em> it is doing, then you should extract it into a function and name the function after the “what”. Then, when you read it again, the purpose of the function leaps right out at you, and most of the time you won’t need to care about how the function fulfills its purpose …” <em>[1, p. 107]</em></blockquote><blockquote>“If the code I want to extract is very simple, such as a single function call, I still extract it if the name of the new function will reveal the intent of the code in a better way. If I can’t come up with a more meaningful name, that’s a sign that I shouldn’t extract the code. However, I don’t have to come up with the best name right away; sometimes a good name only appears as I work with the extraction. It’s OK to extract a function, try to work with it, realize it is not helping, and then inline it back again. As long as I’ve learned something, my time wasn’t wasted.” <em>[1, p. 107]</em></blockquote><blockquote><em>“Often, a good way to improve a name is to write a comment to describe the function’s purpose, then turn that comment into a name.” </em>[1, p. 125]</blockquote><p>About Encapsulate Variable:</p><blockquote>“The greater the scope of the data, the more important it is to encapsulate.” <em>[1, p. 132–133]</em></blockquote><blockquote>“My approach with legacy code is that whenever I need to change or add a new reference to such a variable, I should take the opportunity to encapsulate it. That way I prevent the increase of coupling to commonly used data.” <em>[1, p. 133]</em></blockquote><blockquote>“If I want to move widely accessed data, often the best approach is to first encapsulate it by routing all its access through functions. That way, I turn the difficult task of reorganizing data into the simpler task of reorganizing functions.”<em> [1, p. 132]</em></blockquote><blockquote>“… the object-oriented approach puts so much emphasis on keeping an object’s data private. Whenever I see a public field, I consider using Encapsulate Variable <em>[writer’s note: one of the refactoring methods]</em> … to reduce its visibility.” <em>[1, p. 133]</em></blockquote><blockquote>“Some … argue that even internal references to fields within a class should go through accessor functions — an approach known as self-encapsulation. On the whole, I find self-encapsulation excessive — if a class is so big that I need to self-encapsulate its fields, it needs to be broken up anyway.”<em> [1, p. 133]</em></blockquote><blockquote>“Keeping data encapsulated is much less important for immutable data. When the data doesn’t change, I don’t need a place to put in validation or other logic hooks before updates. I can also freely copy the data rather than move it — so I don’t have to change references from old locations, nor do I worry about sections of code getting stale data. Immutability is a powerful preservative.” <em>[1, p. 133]</em></blockquote><p>About Combining Functions into Transform:</p><blockquote>“… a data transformation function … takes the source data as input and calculates all the derivations, putting each derived value as a field in the output data.”<em> [1, p. 149]</em></blockquote><p>About Removing Flag Argument:</p><blockquote>“A flag argument is a function argument the caller uses to indicate which logic the called function should execute.”<em> [1, p. 314]</em></blockquote><blockquote>“I dislike flag arguments because they complicate the process of understanding what function calls are available and how to call them … Boolean flags are even worse since they don’t convey their meaning to the reader — in a function call, I can’t figure out what true means. It’s clearer to provide an explicit function for the task I want to do [writer’s note: Instead of e.g. bookConcert(aCustomer, true), use premiumBookConcert(aCustomer)].” <em>[1, p. 315]</em></blockquote><h3>Is the Book Outdated?</h3><p>My main issue with the book is that some of the refactorings have become obsolete with the rise of automatic refactoring in the IDEAs (e.g. think “Rename Symbol” in VS Code). Fowler argues in the book that the list of steps for each refactoring is small to make it easier to revert if an error occurs. But I was surprised of <em>how </em>small the steps actually were.</p><p>For a senior developer, some of the steps are so obvious that it seems unnecessary to see it spelled out. E.g. from the subchapter “Extract Function”: <em>“Copy the extracted code from the source function into the new target function”</em> [1, p. 106].</p><p>Fowler points this out however, that the rise of automatic refactorings have changed the landscape. It was interesting to read some of the history of automatic refactoring that Fowler has included in the book. It made me realize that I, as a developer born in the 1990s, simply take automatic refactoring in the IDEA for granted, when a huge effort has been made in order to make refactoring easier today.</p><p>Another problem with the book that makes it feel outdated to me, was how it explained Continuous Integration (CI) and why branches should be small. CI seems so obvious in todays programming world that it is weird reading about it as if it was an option. This was yet an example of how developers my age take processes for granted that has solved past issues. It was nevertheless educational to read how it was “back in the days”.</p><p>For these reasons, a developer with my age and experience might not appreciate the book in the way it deserves despite its historic significance. To try rectify this, let’s end this subchapter with a quote from the book to help us remember its significance:</p><blockquote>“Twenty years ago <em>[writer’s note: That is around year 2000, given this sentence was time adjusted in the second edition]</em>, the conventional wisdom was that to get this kind of good design, it had to be completed before starting to program — because once we wrote the code, we could only face decay. Refactoring changes this picture. We now know we can improve the design of existing code — we can form and improve a design over time, even as the needs of the program change. Since it is very difficult to do a good design up front, refactoring becomes vital to achieving that virtuous path of rapid functionality.”<em> [1, p. 50]</em></blockquote><h3>Who Should Read This Book?</h3><p>The book is definitely worth a read if you are interested in programming history. It is also a great read if you want to exercise your brain on some old school JavaScript class and inheritance code. If however you are interested in maximising your learning towards refactoring and what good code really is, I would recommend finding more up to date resources – maybe a book written with the 2020s as a starting point, instead of a book that has to explain how its content relates to its first edition written in 1999 :)</p><h3>What to Read Next?</h3><p>The book many times refers to the<a href="https://martinfowler.com/bliki/GangOfFour.html"> “Gang of Four” book</a>, and calls it “highly influential”. In my quest to understand more if the “old days” as an attempt to make me a better developer in these “new days”, it seems like a obligatory read.</p><p>Also because legacy code usually at some point becomes a part of a developers job, the book <a href="https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052">“Working Effectively with Legacy Code”</a> by Michael Feathers that the book mentions, seems like a desirable read.</p><h3>References</h3><p>[1] Martin Fowler, with contributions by Kent Beck: Refactoring, Improving the Design of Existing Code. Second edition. 2019.</p><h3>List of Refactorings</h3><p>As they are presented as subchapters in chapter 6–12 in [1, p. 105–404]:</p><p>Ch. 6: A First Set of Refactorings</p><ul><li>Extract Function:</li><li>Inline Function</li><li>Extract Variable</li><li>Inline Variable</li><li>Change Function Declaration</li><li>Encapsulate Variable</li><li>Rename Variable</li><li>Introduce Parameter Object</li><li>Combine Functions into Class</li><li>Combine Functions intro Transform</li><li>Split Phase</li></ul><p>Ch. 7: Encapsulation</p><ul><li>Encapsulate Record</li><li>Encapsulate Collection</li><li>Replace Primitive with Object</li><li>Replace Temp with Query</li><li>Extract Class</li><li>Inline Class</li><li>Hide Delegate</li><li>Remove Middle Man</li><li>Substitute Algorithm</li></ul><p>Ch. 8: Moving Features</p><ul><li>Move Function</li><li>Move Field</li><li>Move Statements into Function</li><li>Move Statements to Callers</li><li>Replace Inline Code with Function Call</li><li>Slide Statements</li><li>Split Loop</li><li>Replace Loop with Pipeline</li><li>Remove Dead Code</li></ul><p>Ch. 9: Organizing Data</p><ul><li>Split Variable</li><li>Rename Field</li><li>Replace Derived Variable with Query</li><li>Change Reference to Value</li><li>Change Value to Reference</li></ul><p>Ch. 10: Simplifying Conditional Logic</p><ul><li>Decompose Conditional</li><li>Consolidate Conditional Expression</li><li>Replace Nested Conditional with Guard Clauses</li><li>Replace Conditional with Polymorphism</li><li>Introduce Special Case</li><li>Introduce Assertions</li></ul><p>Ch. 11: Refactoring APIs</p><ul><li>Separate Query from Modifier</li><li>Parametrize Function</li><li>Remove Flag Argument</li><li>Preserve Whole Object</li><li>Replace Parameter with Query</li><li>Replace Query with Parameter</li><li>Remove Setting Method</li><li>Replace Constructor with Factory Function</li><li>Replace Function with Command</li><li>Replace Command with Function</li></ul><p>Ch.12: Dealing with Inheritance</p><ul><li>Pull Up Method</li><li>Pull Up Field</li><li>Pull Up Constructor Body</li><li>Push Down Method</li><li>Push Down Field</li><li>Replace Type Code with Subclass</li><li>Remove Subclass</li><li>Extract Superclass</li><li>Collapse Hierarchy</li><li>Replace Subclass with Delegate</li><li>Replace Superclass with Delegate</li></ul><p>[1] Martin Fowler, with contributions by Kent Beck: Refactoring, Improving the Design of Existing Code. Second edition. 2019.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d724c146f774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personalization — The Good And The Bad]]></title>
            <link>https://forsethingvild.medium.com/personalization-the-good-and-mostly-the-bad-0ebc465a657c?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ebc465a657c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[personalization]]></category>
            <category><![CDATA[nielsen-norman-group]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Wed, 14 May 2025 18:26:53 GMT</pubDate>
            <atom:updated>2025-05-15T13:21:47.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Personalization — The Good And The Bad</h3><p>Everyone is fighting for the users’ attention and time online. The competition is as hard as ever. This means that the right content needs to be showed immediately. Personalization is in other words inevitable. This article however aims to nuance the benefit of personalization, and give insight on the complexity it adds to your code base.</p><p>I work as web developer one of the biggest streaming platforms in Norway. We recently rewrote the front page to support full personalization — every user should get series recommended to them tailored to their taste. The result can be seen on <a href="http://tv.nrk.no/">tv.nrk.no</a> — just imagine a Norwegian type of Netflix.</p><p>The lessons we learned are the following : 1. The data API needs to be refactored 2. Less is cacheable 3. Loading states need to be designed 4. Need to think differently about accessibility (a11y).</p><h3>The data API needs to be refactored</h3><p>The API that delivered the data to our site, needed to be change in order to make personalization possible. Before, every user got the same big payload that before compression was about 1 MB. In the new API design, we download just a skeleton (15 kB) with references (tailored to the user). Then, in subsequent requests, small units of data (1 kB each) for each reference is fetched as the users scrolls them into view. This is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maijc-PQEgF6YbXoEA-I2g.png" /><figcaption>The illustration shows that before, the API delivered on big response for all users. After, it delivers a skeleton of references (tailored to the users taste) instead, then the actual units of data is fetched in subsequent requests.</figcaption></figure><p>It is evident that with the new approach, a lot of data was saved. Before a user scrolls, only an average of 60 kB is downloaded from the API, whereas 1 MB before. Roughly estimated based on actual traffic before and after, 75 % of data was saved (which for us is up to 250 GB per day!), which is both economically and environmental friendly.</p><p>I’ve build a small <a href="https://codepen.io/ingvild/pen/zxOPWMZ">CodePen here</a> to exemplify how we fetch the data as the user scrolls. The video below shows how the data is fetched firstly when the data is supposed to be in view (only for illustrative purposes though, on our production site, we always make sure to fetch the data before it is actually in view — we don’t want the user to actually see the data loading, if it’s avoidable).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Gm9Yp7P6B3IcCruDU8yRLA.gif" /><figcaption>A streaming platform example that shows how units of data is loaded as the user scrolls.</figcaption></figure><h3>Less is cacheable</h3><p>However, the data savings are more nuanced than this. Our streaming platform uses a content delivery network (CDN). A CDN has geographically strategically placed nodes in which data can be cached. The result is that data is downloaded faster, since these nodes are closer to the user. The benefit is smaller when less of the content can be cached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqHjmqLWATcVHJfcWsu27g.png" /><figcaption>Illustration of a CDN. A CDN has geographically strategically placed nodes closer to the end user. Data from the server is cached in the nodes so the user can download the content faster.</figcaption></figure><p>Although we saved 75% of bytes going over the wire, our cache hit at the CDN nodes went down from 85% to 70%. This means that more of the requests hit our server, and more bytes travel a <em>longer</em> <em>distance</em> than before, which comes at a cost.</p><p>In addition to API responses, we also cache the initial HTML of our webpage in the CDN. The caching rules are based on e.g. cookies and search query parameters. These rules needed to be redefined because of the personalization. The result was a higher number of “cache buckets” (the number of different html responses stored in the cache), as can be seen in the illustration below. A higher number of cache buckets means that the cache hit is lowered, which is unfortunate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxw8qoH1Y9ZUTxK5ry-BnQ.png" /><figcaption>Illustration of how the cache buckets for initial HTML increased. More cache buckets means the cache hit is lowered.</figcaption></figure><p>The situation was made even worse by the fact that the content of the cached HTML needed to change. A little back story is required at this point. Some years ago, we took the architectural choice of building our webpage as an <a href="https://www.orientsoftware.com/blog/spa-vs-mpa/">MPA instead of an SPA</a>. The main selling point was that an MPA yields fast initial rendering, since all the markup is delivered by the server, instead of having to wait for JavaScript to download, in order to show the content. With personalization, this benefit became less evident, as can be seen in the illustration below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rmg4VAyt_gdimPlnBAyx9g.png" /><figcaption>Showing what can be cached in the CDN network before versus after. The left image shows our MPA solution without personalization, the right image shows our MPA solution with personalization.</figcaption></figure><p>Lighthouse analyses gave us the true hard facts. Below is the webpage shown before and after how Lighthouse saw it during the analyses. Our <a href="https://developer.chrome.com/docs/lighthouse/performance/first-contentful-paint">FCP</a> increased from 0.9 s to 1.3 s, <a href="https://developer.chrome.com/docs/lighthouse/performance/lighthouse-largest-contentful-paint">LCP</a> from 2.4 s to 3.6 s, and the <a href="https://developer.chrome.com/docs/lighthouse/performance/speed-index">speed index</a> from 0.9 s to 2.2 s. Of course, there are remedies to this, and we added some, but it adds complexity to your code base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIlwNX-jvtOdDLmRvvLYxw.png" /><figcaption>Screenshot of what Lighthouse sees during a performance analysis, before versus after. It is evident that it takes a longer time before the user sees a webpage that resembles close to finished.</figcaption></figure><h3>Loading states need to be designed</h3><p>One such remedy to help improve the user experience as waiting time increases, is implementing loading states. <a href="https://www.nngroup.com/articles/progress-indicators/">Progress indicators have showed to make a slow system less insufferable</a> (NN/group). In our case, we added a<a href="https://www.nngroup.com/articles/skeleton-screens/"> skeleton screen</a> as visual feedback while the data loads. The illustration below shows the flow that meets the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwpgoR09EPlW9HEMfpBY7g.png" /><figcaption>Illustration showing the flow that meets the user web when visiting the webpage. An intermediate skeleton step is added while the data is downloading to give some visual feedback to the users that something is happening to keep their attention.</figcaption></figure><p>Why is this important? According to the well known UX experts at the NN/group, these are the <a href="https://www.nngroup.com/articles/website-response-times/">response time limits that apply to the web platform</a>:</p><ul><li><strong>1 second</strong> keeps the user’s flow of thought <strong>seamless</strong>.</li><li><strong>10 seconds</strong> keeps the user’s <strong>attention</strong> […] A 10-second delay will often make users leave a site immediately.</li></ul><p>If we assume this to be true, we broke the user’s flow when increasing the time of FCP from 0.9 s to 1.3 s after the refactoring to support personalization.</p><p>The increased waiting time was a technical consequence that we had failed to warn the designers about. As a result, a unified loading state design across the different platforms was not in place. The implementation process would have been much more seamless if the total user experience, from writing the url in the address bar to actually seeing the personalized content, had been thought of it advance.</p><h3>Need to think differently about a11y</h3><p>We also failed to understand the impact of personalization on the screen reader experience in advance. The main concern we failed to recognize, was the difference it made to a11y when the data was no longer available from the start, but fetched as the user scrolled. We ended up with a broken screen reader experience with VoiceOver in Safari because of it. Here are the special measures we took to fix it:</p><ul><li>Our placeholders for content that was loading was anchor tags, but without any href attribute, since the path had yet to be downloaded.</li><li>Anchor tags without href was not focusable/reachable with via keyboard navigation.</li><li>The data needed to be in view to be downloaded, but to be in view, they had to be focusable — it became a vicious cycle kind of problem!</li><li>Therefore, we added a temporary href value of # while loading to solve the issue.</li><li>This problem was enhanced by the fact we used the new intersection observer option property scrollMargin, which we falsely thought we could use as a progressive enhancement. We knew it would mean that Safari would not load data before it was actually in view. However, we did not realize it resulted in the content being unreachable when navigating with screen reader controls, so we had to stop using it. I’ve written more about the problem on the Frontend Masters blog <a href="https://frontendmasters.com/blog/simplify-lazy-loading-with-intersection-observers-scrollmargin/">here</a>.</li></ul><p>One can say the issues was caused by bugs in the Safari implementation perhaps. Regardless, we as web developers should in my opinion aim for browser diversity and make webpages that work in more than one browser.</p><p>(Update : Since writing this article, support for scrollMargin has been added to Safari according to <a href="https://bugs.webkit.org/show_bug.cgi?id=263370">this issue</a> 🎉)</p><p>In this article, we have investigated four main areas that gets affected when personalizing your webpage to your customers: The data API needs to be refactored, less is cacheable, loading states need to be designed, and one has to think differently about a11y. I’ve tried to nuance the consequences of implementing a personalized webpage, both technically and when it comes to the user experience, as I understood it at the time of writing.</p><p>I hope this article can help you understand what to expect as a developer when stakeholders decide to prioritize personalization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ebc465a657c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typography Bits & Pieces]]></title>
            <link>https://forsethingvild.medium.com/typography-bits-pieces-15628dc1c279?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15628dc1c279</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[typography]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 15:31:49 GMT</pubDate>
            <atom:updated>2024-12-02T15:31:49.051Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is inspired by<a href="https://youtu.be/WdBNYcWG0Yg?si=eprnpRyu1gv2GPIP"> Kevin Powells talk with Roel Nieskens on Youtube “CSS Typography Crash Course”</a>, and also <a href="https://youtu.be/TreBK-EyACQ?si=tp8taffElsFAAHGN">Roel Nieskens talk on CSS Day 2024 “Problems solved by OpenType”</a>. But, I needed a fast lookup to the tips &amp; tricks in these videos, so that is why I created this post, so I did not have to watch an entire video each time I forgot the details. Hopefully, this post can benefit you as well.</p><p><em>Disclaimer: This article should be considered almost a transcript of the </em><a href="https://youtu.be/WdBNYcWG0Yg?si=eprnpRyu1gv2GPIP"><em>Youtube video “CSS Typography Crash Course”,</em></a><em> and all credits should go to </em><a href="https://www.kevinpowell.co/"><em>Kevin Powell</em></a><em> and especially </em><a href="https://pixelambacht.nl/"><em>Roel Nieskens</em></a><em> for all the information and code examples included in this article.</em></p><h3>Wakamaifondue.com</h3><p>Roel Nieskens has created <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a>. It is a place you can upload e.g. your variable font, and then get information of the possible ranges for weight and width, other font-feature settings that are available and unique to the font etc. This is because font files includes metadata about the font, but it is not so available for the human eye as is in the file, so uploading it to a service that allows you the better grasp it’s possibilities is usually a good idea. <a href="https://fontdrop.info/">FontDrop!</a> seems to be an other option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*H9x8TZifu-1s0W6w_7W9PA.jpeg" /><figcaption>Some of the things what meets you at <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a> (per 02.12.24). You can upload a variable font, and then get information of the features it offers, such as the available width and weight ranges.</figcaption></figure><h3>Variable fonts can have custom axes</h3><p>For variable fonts, there are five registered axes: the font weight, the font width (CSS property font-stretch is used for this), italic, slant and optical sizing. More about these <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_fonts/Variable_fonts_guide#registered_axes_and_existing_css_attributes">registered variable font axes can be read about here on MDN</a>. However, the font designer can create <em>custom </em>axes unique for the font, and it is exactly information like that, that can be more easily accessed using a service like <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a>.</p><p>For custom axes, the CSS property font-variations-settings needs to be used (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-variation-settings">read more about the font-variation-settings on MDN here</a>). This property can also be used for the aforementioned registeres axis, but usually the dedicated CSS properties like font-weight, font-strecthand font-style are used for those. The syntax is:</p><p>font-variation-settings: &lt;axis name&gt; &lt;axis range value&gt;</p><p>So for a variable font that has a custom axis called “SOFT”, you can write font-variation-settings: ‘SOFT’ 50;. Available custom axes for a particular font, is exactly what <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a> can help you discover.</p><p>You can also transition and animate the custom axes, by e.g. including something like transition: font-variation-settings 1s; in your code.</p><h3>Color fonts</h3><p>At the same time as variable fonts were added to the Open Type spec, color fonts were added. They are at the time being less known and used compared to variable fonts, but for the especially interested developer, they can be great fun to work with.</p><p>Roel gives us an example of the <a href="https://www.typearture.com/product/magical-unicorn-neue-pro/">Magical Unicorn Neue Pro color font created by Typearture</a>, which is shown in the image below. It creates all letters using elements of a unicorn an its world. Uploading the font in <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a>, will show you the color palette a color font uses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*NOMZ1Ukw6IF7o8MvHL597g.png" /><figcaption>The <a href="https://www.typearture.com/product/magical-unicorn-neue-pro/">Magical Unicorn Neue Pro color font created by Typearture</a> is a font in which each letter is created using elements from a unicorn. Uploading the font to <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a> will show you the color palette the color font uses.</figcaption></figure><p>In a color font, you can override colors used in the color palette that the font uses. For the color font used as an example above, we can e.g. override just the color of the unicorn’s hair. To do this, we need to declare a @font-palette-values property. The following code can be used to change the color of the unicorn’s hair to lime green 🦄.</p><pre>/* <br>  Code snippet by Roel Nieskens, slightly altered.<br>  See https://youtu.be/WdBNYcWG0Yg?si=B9LaRn-01bwoHJ7f&amp;t=1956 for reference. <br>*/<br>@font-face {<br> font-family: Unicorn;<br> src: url(https://medium.com/&lt;path%20to%20where%20you%20host%20the%20font&gt;);<br>}<br><br>@font-palette-values --lime-unicorn-hair {<br> font-family: Unicorn;<br> override-colors: 4 lime;<br>}<br><br>h1 {<br> font-family: Unicorn;<br> font-palette: --lime-unicorn-hair;<br>}</pre><p>Some color fonts come with several base palettes. For example <a href="https://www.typearture.com/">Typearture</a>’s font Mechatron comes with several palettes designed by the font designer. As always, you can upload the font to <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a> to see which palettes are available, and then choose a different one using the @font-palette-values declaration in this way:</p><pre>/*<br>  Code snippet by Roel Nieskens.<br>  See https://youtu.be/WdBNYcWG0Yg?si=B9LaRn-01bwoHJ7f&amp;t=1956 for reference.<br>*/<br>@font-palette-values --robot {<br> font-family: Mechatron:<br> base-palette: 2;<br>}<br><br>h1 {<br> font-palette: --robot;<br>}</pre><h3>Practical Open Type features that can improve readability</h3><p>Leaving the more creative and fun sides of fonts, Nieskens continues to show us some <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_fonts/OpenType_fonts_guide">OpenType features</a> that he thinks are not used enough on the web today (per 02.10.24). These should be used to help improve readability on your page.</p><p>Nieskens says that these are the kind of features that if we were to read a book and they were turned off, the reading experience would be degraded. It is something we take for granted in our analog reading experiences, and we should start utilizing them also on the web platform.</p><p>Thus, upload your font to <a href="https://wakamaifondue.com/">https://wakamaifondue.com/</a> and see what kind of features it supports! Here are the practical ones Nieskens drew focus to as features that many projects could benefit from utilizing.</p><h4>font-variant-numeric: tabular-nums;</h4><p>font-variant-numeric: tabular-nums; can be used to make sure each digit takes the same width. This helps reading numbers in e.g. tables, as each digit will line up. This feature can be used instead of applying a separate monospace, which is what some people do to achieve exactly this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*HHoGVRk2ji2Gwgp-IXxvhQ.png" /><figcaption>font-variant-numeric: tabular-nums; is not on in the leftmost example, which leaves the second column ragged and it is difficult to compare the numbers. The feature is turned on in the rightmost example, which makes it easier to compare the numbers.</figcaption></figure><h4>font-variant-numeric: oldstyle-nums;</h4><p>font-variant-numeric: oldstyle-nums; changes numbers to lowercase letters, which is probably what you will find in books. The change is evident, as can be seen in the image below, and makes numbers more subtle when they are inline in a text reading a text. The numbers no longer “shouts” at the reader, and it yields a more pleasent reading experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*i3J-PiYElRVzlS9NM2MCKw.png" /><figcaption>Image showing text <em>before font-variant-numeric: oldstyle-nums; is turned on.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Ls_alRVSXzkBElklRodH7g.png" /><figcaption>Image showing text <em>after font-variant-numeric: oldstyle-nums; is turned on. It makes the year “1994” change the numbers to take the lowercase height.</em></figcaption></figure><h4>font-variant-caps: all-small-caps;</h4><p>font-variant-caps: all-small-caps; is perfect for abbreviations. It keeps the letters uppercased, but at the height of the lower case characters. The result is the same when using oldstyle-nums for numbers — the abbreviations draws less attention from the reader because they take less space, and the reading experience is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmS9yiyoZBs-EgLqinb23Q.png" /><figcaption>Image showing text before font-variant-caps: all-small-caps; is turned on.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wB5mD4Agbxr_1rIvKr5pA.png" /><figcaption>Image showing text after font-variant-caps: all-small-caps; is turned on. It makes the abbreviations WWW and CERN take the lowerheight case, so the abbreviations “</figcaption></figure><h4>font-feature-settings: “sinf”;</h4><p>font-feature-settings: “sinf&quot;; is used for scientific text, such as chemical symbols where the numbers should be subscripted. See the examples below how this settings makes the chemical symbols look as they should.</p><p>For those extra interested: This feature is turned on using the font-feature-settings CSS property, since it is not yet supported as a font-variant. The font-feature-settings CSS property differs from the previously used font-variant-&lt;some variant&gt; CSS because when we use it, we are adressing the font directly and bypassing the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuDsAcRuZHqwP1IhRxl0ug.png" /><figcaption>Image showing text before font-feature-settings: “sinf&quot;; is turned on. The numbers in chemical symbols such as the one for Carbon dioxide (CO2) have the same height as the letters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYMKR-sfnDyT8w2RTdVjhA.png" /><figcaption>Image showing text after font-feature-settings: “sinf&quot;; is turned on. The numbers in chemical symbols such as the one for Carbon dioxide (CO2) are subscripted, which makes them look scientifically correct.</figcaption></figure><h4>font-variant-numeric: diagonal-fractions;</h4><p>font-variant-numeric: diagonal-fractions; can be used whenever you have fractions on your page. This is particularly relevant for cooking recipes. It makes each number of the fraction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*BDU7bX8W3mCiqKpGR4pPoA.png" /><figcaption>Image showing text before font-variant-numeric: diagonal-fractions; is turned on. The numbers in the fraction takes the whole space like they do if they were to appear outside a fraction.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*5DsdDBbJCsvP17ppU6Wiaw.png" /><figcaption>Image showing text after font-variant-numeric: diagonal-fractions; is turned on. The numbers in the fraction are made smaller so the fraction takes less space</figcaption></figure><p>So where can you find fonts to play with? Of course <a href="https://fonts.google.com/">Google Fonts</a> offer a great selection of and easy to use fonts, but Nieskens also recommends <a href="https://v-fonts.com/">V-Fonts</a> for a range of variable fonts particularly, and also to support creative and more indie font creators, which can be found at e.g. <a href="https://type-atlas.xyz/">type-atlas.xyz</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15628dc1c279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Helpful CSS Acronyms]]></title>
            <link>https://forsethingvild.medium.com/helpful-css-acronyms-d16010e5dd5f?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16010e5dd5f</guid>
            <category><![CDATA[keith-grant]]></category>
            <category><![CDATA[josh-comeau]]></category>
            <category><![CDATA[hsl]]></category>
            <category><![CDATA[ben-frain]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 10:26:34 GMT</pubDate>
            <atom:updated>2024-03-27T09:19:38.539Z</atom:updated>
            <content:encoded><![CDATA[<p>Over time, I have gathered a small collection of CSS acronyms that I use to avoid looking up the CSS documentation, or to simply just write correct CSS. CSS in itself is an acronym, meaning “Cascading Style Sheets”, but lets take a look at my self-invented/self-collected list of CSS acronyms that hopefully can help your everyday CSS life.</p><h3>TRouBLe</h3><p>This one is already well-known, but it can be fairly useful, especially for junior CSS developers. Have you ever forgotten the order of the CSS properties in the shorthand property for e.g. margin ? The order is <strong>TRouBLE!</strong>:</p><p>margin: &lt;<strong>T</strong>op margin&gt; &lt;<strong>R</strong>ight margin&gt; &lt;<strong>B</strong>ottom margin&gt; &lt;<strong>L</strong>eft margin&gt;;</p><p>CSS tricks wrote <a href="https://css-tricks.com/remember-the-order-of-marginpadding-shorthand-with-trouble/">a post</a> about this acronym already in 2007.</p><h3>Lord Vader Hates Fluffy Animals</h3><p>This acronym was discovered due to a bug in production had to be solved, so it is probably my favorite. <strong>Lord Vader Hates Fluffy Animals </strong>helps you get the order of styles for your links, your &lt;a&gt; tags, correct. The order should be this:</p><pre>a {...}<br>a:visited {...}<br>a:focus {...}<br>a:hover {...}<br>a:active {...}</pre><p>This is due to the fact that you want your active links to overwrite the style for the hovered ones, which again should override the style if the link is active etc.</p><p>The order, however, can be up for the discussion, in the sense that it <em>can </em>be argumented that the focus state should override the hover state. I <em>think </em>the bug in production was solved choosing <strong>Lord Vader Fluffy Hates Animals </strong>instead, whatever that means 😉 Feel free to leave a comment if you have any great insight into this 👍</p><p>Either way, this acronym has helped me personally get my CSS styles right, so I would <em>absolutely </em>recommend. I will leave you with a AI generated image of this acronym, hoping that the visual will help the memory with remembering this useful acronym ⬇️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*TFhANlDXK1qCvqpbdZXczA.png" /><figcaption>Lord Vader dressed as a fluffy cat (and so he hates fluffy animals? 😆). (Source: AI image generator tool <a href="https://www.craiyon.com/">Craiyon</a>.)</figcaption></figure><p>The credit for this acronym goes to <a href="https://keithjgrant.com/">Keith Grant</a> and his book <a href="https://www.amazon.com/CSS-Depth-Keith-J-Grant/dp/1617293458">CSS in Depth</a> (1st edition from 2018), in which I learned this acronym. I would definitely recommend the book, and you can read more about it in my blog post <a href="https://forsethingvild.medium.com/books-you-can-read-to-learn-css-6f76510af8e8#1e24">here</a>.</p><p>Lastly, it exists other acronyms to help with remembering this correct order. <strong>LoVe HAte</strong> (<strong>l</strong> for link, <strong>v</strong> for visited, <strong>h</strong> for hover, <strong>a</strong> for active) has been around for some while, as can be seen from this <a href="https://css-tricks.com/remember-selectors-with-love-and-hate/">CSS Tricks post</a> from 2007.</p><h3>Young Guys Can Be Messy Radicals</h3><p>Have you ever watched or read some tutorial by a <em>really</em> smart web developer that navigates the HSL 360 degree color wheel like a pro? Ever gotten that uneasy feeling when you then realize you don’t know the cool wheel as good as obviously would be beneficial? <strong>Young Guys Can Be Messy Radicals </strong>to the rescue! If you rotate around the color wheel (you can use the image ⬇️ to check), the order is <strong>y</strong>ellow (y for young), <strong>g</strong>reen (guys for green), <strong>c</strong>yan (c for cyan), <strong>b</strong>lue (b for be), <strong>m</strong>agenta (m for magenta), <strong>r</strong>ed (r for red).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jebcsHOvsdB4VebsgNTs7A.png" /><figcaption>The HSL/HSV color wheel. (Source: <a href="https://stackoverflow.com/users/8704818/kevin-hu">Kevin Hu</a> in <a href="https://stackoverflow.com/questions/62531754/how-to-draw-a-hsv-color-wheel-using-matplotlib">this StackOverflow-post</a>, 23.05.23)</figcaption></figure><p>The credit for this acronym/rule of thumb, is the book <a href="https://www.amazon.com/Responsive-Web-Design-HTML5-CSS/dp/180324271X">“Responsive Web Design with HTML5 and CSS” by Ben Frain</a>, p.197 (4th edition from 2022).</p><p>Also, I want to recommend the <a href="https://www.smashingmagazine.com/2021/07/hsl-colors-css/">“Using HSL Colors In CSS” tutorial on Smashing Magazine</a> (from July 2021), as a great introduction on how to utilize the HSL color format to organize your design system colors into CSS custom properties effectively. I also recommend the <a href="https://www.joshwcomeau.com/css/color-formats/">“Color Formats in CSS” post by Josh Comeau</a>, in which he tries to give some examples on the use cases on when it is the correct to use the different color formats in CSS.</p><p>I hope these acronyms can be helpful for someone. The credit of course goes to the respective authors of these great rules of thumb for writing CSS (<a href="https://keithjgrant.com/">Keith Grant</a> and <a href="https://benfrain.com/">Ben Frain</a>!). I also lastly want to give a BIG shoutout to at the time my closest colleague, <a href="https://phajsi.com/">Phajsi</a>, who has helped me keeping the list of CSS acronyms up-to-date ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16010e5dd5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Books you can read to learn CSS]]></title>
            <link>https://forsethingvild.medium.com/books-you-can-read-to-learn-css-6f76510af8e8?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f76510af8e8</guid>
            <category><![CDATA[erik-meyer]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[lea-verou]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[josh-w-comeau]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 08:52:23 GMT</pubDate>
            <atom:updated>2023-03-10T09:37:40.399Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2022, I set out with a goal to read some of the CSS books out there to see how it would be to learn CSS to a greater extend “bottom up”. Here is a review of each of them, so maybe you more easily can take a qualified choice of what books to read, if you are interested in taking the same approach.</p><h3>“CSS: The Definitive Guide” by Erik A. Meyer and Estelle Weyl</h3><p>This book can be really recommended, it is long, about a thousands pages long — but it teaches you CSS from the bottom and up, even including some of it’s interesting history! The chapters are greatly dividing the different CSS properties in a sensible way, explaining each CSS property throughly one at a time. “CSS: The Definitive Guide” can be found on <a href="https://www.amazon.com/CSS-Definitive-Guide-Visual-Presentation/dp/1449393195">Amazon</a> from $28 (used).</p><p>With chapters like <em>“Specificity and the Cascade”</em>, <em>“Animation”</em> or <em>“Grid Layout”</em>, and at the end a great index, it is easy to search and find what you are looking for using the book. The book even has a humorous tone to it, making it at times even a bit funny to read. It is perhaps not the book you would read at one go, so I would recommend this book first and foremost to experienced CSS developers knowing what they want to learn more about. Also, a great convenience would be if the book was split into smaller pockets books. You feel a bit of a scientist almost when bringing a thousand pages big book under your arm to help solve a problem, when you know e.g. the “Animation” chapter is all you are going to need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*fKH-VAopNcIcLRrZbrCXVw.png" /><figcaption>CSS: The Definitive Guide written by Erik A. Meyer &amp; Estelle Weyl is a great read (<a href="https://www.amazon.com/CSS-Definitive-Guide-Visual-Presentation/dp/1449393195">image source</a>).</figcaption></figure><h3>“CSS Pocket Reference” by Erik Meyer</h3><p>I have not read this back-to-back, as it is more of a pocket book you can easily turn up things. It works as an alternative to <a href="https://developer.mozilla.org/en-US/docs/Web">MDN Web Docs</a> to keep on your desk to switch things up and not always turn to your computer to look up some CSS property. I have always been a fan of books and the tactile feel it gives, so I enjoy using this at times. A big bonus is off course that is yet again the oh-so-famous and CSS important figure Eric Meyer that is the author. “The CSS Pocket Reference” can be found on <a href="https://www.amazon.com/CSS-Pocket-Reference-Visual-Presentation/dp/1492033391/ref=sr_1_1?crid=1964C3410DJ0V&amp;keywords=CSS+pocket+reference+5th+guide&amp;qid=1678433393&amp;s=books&amp;sprefix=css+pocket+reference+5th+guide%2Cstripbooks-intl-ship%2C156&amp;sr=1-1">Amazon</a> for $8.83 (used).</p><p>Being an another O’Reilly product, it works as a great addition to the “CSS: The Definitive Guide”. One thing to have in mind though, is that off course it will get outdated and not have the latest specification included, but I would say that the CSS does not evolve <em>that </em>fast currently for it to be a problem. Also, it seems to get fairly often updated, being on it’s 5th edition currently.</p><figure><img alt="The book cover of the book “CSS Pocket Reference” written by Eric Meyer." src="https://cdn-images-1.medium.com/max/638/1*OlogxEL73uHRY8K9sFMIlQ.png" /><figcaption>The CSS Pocket Reference by Eric Meyer is a great addition to have on your desk if you like the tactile feel of books instead of always turning to your computer to read about a specific CSS property or value (<a href="https://www.amazon.com/CSS-Pocket-Reference-Visual-Presentation/dp/1492033391/ref=sr_1_1?crid=1964C3410DJ0V&amp;keywords=CSS+pocket+reference+5th+guide&amp;qid=1678433393&amp;s=books&amp;sprefix=css+pocket+reference+5th+guide%2Cstripbooks-intl-ship%2C156&amp;sr=1-1">image source</a>).</figcaption></figure><h3>“CSS Secrets: Better Solutions to Everyday Web Design Problems” by Lea Verou</h3><p>I’ve always been a <em>big </em>fan of Lea (just take a look at <a href="https://forsethingvild.medium.com/lea-verous-dynamic-css-secrets-takeaways-d281218de60a">this post</a>), so of course I found her book “CSS Secrets: Better Solutions to Everyday Web Design Problems” really intriguing. Lea’s own words are that this book is suitable for “intermediate to advanced” CSS developers, which makes sense, because the book is a series of solutions to typical CSS challenges most web developers doing CSS have experienced, and gotten crazy about thinking: “why is the solution to this simple issue <em>that</em> comprehensive”? “CSS Secrets: Better Solutions to Everyday Web Design Problems” can be bought on <a href="https://www.amazon.com/CSS-Secrets-Solutions-Everyday-Problems/dp/1449372635/ref=sr_1_1?keywords=css+secrets+better+solutions+to+everyday+web+design+problems&amp;qid=1678437853&amp;sprefix=css+secre%2Caps%2C178&amp;sr=8-1">Amazon</a> for $2.93 (used).</p><p>The book includes 47 secrets that are grouped into seven chapters like <em>“Backgrounds and Borders”</em>, <em>“Typography” </em>and <em>“Transitions and Animations”</em>. There is also an overview of the different secrets grouped by CSS specification (like <a href="https://drafts.csswg.org/css-animations">“CSS Animation” </a>or <a href="https://drafts.csswg.org/css-backgrounds-4/">“CSS Backgrounds &amp; Borders Level 4”</a>, including a link to each corresponding <a href="https://www.w3.org/">W3C</a> spec). The secrets included are solutions to challenges like the ones listed below ⬇️, so I would <em>definitely</em> recommend this book if you find some of these intriguing:</p><ul><li>Striped backgrounds</li><li>Simple pie charts</li><li>Folded corner effect</li><li>Zebra-striped text lines</li><li>Ligatures</li><li>Circular text</li><li>Fluid background, fixed content</li><li>Vertical centering</li><li>Sticky footers</li><li>How to get an animation along a circular path.</li></ul><p>… to mention a few (of 47!) 😮‍💨</p><p>The fact that the book is simply written with HTML styled with CSS (4 700 lines of SCSS!), and also have its preface written by the yet again oh-so famous and already mentioned Eric Meyer, makes this book just perfect for CSS nerds 👍 It also includes CSS coding tips, and also some background information about the typical standard process behind the W3C specs, and explains the different CSS spec levels (CSS 1, CSS 2 etc.), which can also come in handy to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*b1OYqbC3CeitGknbsf5v7w.png" /><figcaption>Lea Verou’s “CSS Secrets: Better Solutions to Everyday Web Design Problems“ is best suitable for developers that already have some experience with CSS (<a href="https://www.kobo.com/no/nb/ebook/css-secrets">image source</a>).</figcaption></figure><h3>“CSS in Depth” by Keith J. Grant</h3><p>This book surprised me, as I remembered thinking <em>“if I was ever to teach a class about CSS, teaching students about CSS from the bottom up, this book would be an </em>excellent<em> choice”</em> (which I would actually really enjoy I think, teaching 🙈). The book is a smaller and less comprehensive alternative to the “CSS: Definitive Guide”, closing in on “only” about 400 pages. “CSS in Depth” can be bough at <a href="https://www.amazon.com/CSS-Depth-Keith-J-Grant/dp/1617293458?dchild=1&amp;keywords=best+css+books&amp;qid=1625175213&amp;sr=8-11&amp;linkCode=sl1&amp;tag=365blottochal-20&amp;linkId=761719bdaed74156dbd8b35e3e182de2&amp;language=en_US&amp;ref_=as_li_ss_tl">Amazon</a> from $23.77 (used).</p><p>The book groups its chapters into four parts. It starts with the part <em>“Reviewing the fundamentals”</em>, perfect for beginners, giving enough information to get you started and feel in control, without adding <em>too </em>much detail that would leave a beginner to CSS confused (I refer to those kind of details that you later on as a more experienced CSS developer would really enjoy knowing the intricacies of 😁). Then it continues with the part <em>“Mastering Layout”</em>, in which Grant among other things manages to make the flexbox layout actually understandable without too much details. The last two chapters are named <em>“CSS at Scale”</em>, and lastly, <em>“Advanced Topics”</em>.</p><p>Grant shares his knowledge generously from his career which he claims has been since the “very beginning” of CSS. The fact that he builds websites that includes the New York Stock Exchange website (2018), does not make it less impressive. The foreword is written by builder of <a href="https://css-tricks.com/">CSS-Tricks</a> and <a href="https://codepen.io/">CodePen</a> co-founder Chris Coyier, which is yet another quality mark that solidifies this book as a great option for CSS beginners, but actually also for seasoned CSS developers that finally wants to read more about how it <em>actually </em>works (both Grant’s and Coyier’s words).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*EKCzRjdMKwns9jYQJttKZg.png" /><figcaption>“CSS in Depth” by Keith J. Grant is a good choice for beginners to CSS and if you want a less comprehensive intro than that the book “CSS: The Definitive Guide” offers (<a href="https://www.amazon.com/CSS-Depth-Keith-J-Grant/dp/1617293458?dchild=1&amp;keywords=best+css+books&amp;qid=1625175213&amp;sr=8-11&amp;linkCode=sl1&amp;tag=365blottochal-20&amp;linkId=761719bdaed74156dbd8b35e3e182de2&amp;language=en_US&amp;ref_=as_li_ss_tl">image source</a>).</figcaption></figure><h4>Psst. Josh W. Comeau’s CSS for Javascript Developers Course</h4><p>Just one last thing, I actually gave Josh W. Comeau’s <a href="https://css-for-js.dev/">CSS for Javascript Developers Course</a> a go last year. I would recommend if you are one to learn through interactive tasks/challenges. I have to admit, I did not complete all the assignments by handing them in, so I did not <em>complete</em> the course the right way, so bear this in mind when reading my words about this course. But it is a <em>great </em>resource that I have no doubt will leave you with <em>tons </em>of CSS knowledge and experience. I’m greatly impressed (and in awe) by Comeau for making this! 🙌 😊</p><p>One things to note is that it is slightly React inspired, so you will learn CSS from slightly a React point of view. For someone who is not using React at their workplace anymore (like me), the course for this reason can feel less relevant. Also, I found it a bit hard later on to find in the course something specific I wanted to read again when in need for it in my work, so personally I would prefer a book with an index over this 🙃 However, I have always been the person to enjoy learning the fundamentals <em>first</em>, then try to do assignments, so if you are more of a person that enjoys learning by doing, the course could be an excellent option for you.</p><p>Another thing to note, is that it is quite expensive, so it might not be as accessible to most people like a book. The basic package costs $149, but for the ultimate package you are closing in on $399. However, if your workplace sponsors courses like that, it is absolutely a great option for learning CSS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f76510af8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lea Verou’s Dynamic CSS Secrets Takeaways]]></title>
            <link>https://forsethingvild.medium.com/lea-verous-dynamic-css-secrets-takeaways-d281218de60a?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d281218de60a</guid>
            <category><![CDATA[lea-verou]]></category>
            <category><![CDATA[css-custom-properties]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 11:09:57 GMT</pubDate>
            <atom:updated>2023-02-10T11:12:39.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Again, this is a summary of a talk, made in order to 1) hopefully learn something and 2) have an easy access to the valuable information that is contained in a ~1h <a href="https://www.youtube.com/watch?v=ZuZizqDF4q8">YouTube video</a>.</p><p>Hopefully, this will help me and anyone in need of it, avoid endless scrubbing in a Youtube video, searching for that specific use case you are looking for a solution for.</p><p>All credit goes to <a href="https://twitter.com/leaverou">Lea Verou</a>, who is such an inspiration and such a cool lady. She is a <a href="https://www.w3.org/2001/tag/">W3C Tag</a> (the technical architecture group that reviews proposals for future specs and writes documents of the underlying architectural principals of the web, belonging to the <a href="https://www.w3.org/Consortium/">World Wide Web Consortium</a>, which is an international community in which member organizations, a full time staff and the public work together to develop web standards, puh!) member. Her day job is however researching and teaching at MIT. She has her own <a href="https://lea.verou.me/">blog</a> too, and has written the book <a href="https://www.amazon.com/CSS-Secrets-Lea-Verou/dp/1449372635?tag=leaverou-20">CSS Secrets: Better Solutions to Everyday Web Design Problems</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZuZizqDF4q8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZuZizqDF4q8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZuZizqDF4q8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f40d4002ac055e662a43489ba21466a7/href">https://medium.com/media/f40d4002ac055e662a43489ba21466a7/href</a></iframe><p>Disclaimer: The code examples in this text are freely edited and does not reflect the exact lines of Lea’s code. Also, the interpretation of each takeaway/tips are my own and should not be understood as Lea’s exact words.</p><p>This article is long and the timestamps underneath each takeaway is where in the presentation Lea has written the takeaway, but she <em>explains</em> each takeaway <em>before </em>the slide showing the takeaway.</p><h3>Takeaway #1: CSS variables are just regular variables</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=522">08:42</a>)</p><p>The example Lea uses to underline this takeaway, is perhaps the most straightforward one, as it shows a pattern that most developers are already familiar with. Her point is that CSS variables are just like regular variables in the sense that they helps reduce lines of code and repetition. The pattern is used to implement style variation of a component.</p><p>Without using css custom properties, different style variations would typically be implemented as shown below, redeclaring CSS properties and giving them a different value for different variations ⬇️ : (the two following code blocks are freely edited for the purpose of simplification and do not reflect the exact lines of Lea’s code)</p><pre>button {<br> border: .1em solid black;<br> color: black;<br>}</pre><pre>button.pink {<br> border: .1em solid pink;<br> color: pink;<br>}</pre><pre>button.green {<br> border: .1em solid green;<br> color: green;<br>}</pre><p>By instead implementing it like this, utilising CSS custom properties, we avoid repeating CSS properties and thereby simplifying the code ⬇️ :</p><pre>button {<br> --color: black; <br> border: .1em solid var(--color);<br> color: var(--color);<br>}</pre><pre>button.pink {<br> --color: pink;<br>}</pre><pre>button.green {<br> --color: green;<br>}</pre><h3>Takeaway #2: Pseudo-private variables succinctly reduce fallback duplication</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=711">11:51</a>)</p><p>Lea proposes to make use of the underscore syntax to introduce the idea of <em>private</em> CSS custom properties, something that has already been utilised in JavaScript and other programming languages for many years already, but that currently had no equivalent in CSS.</p><p>In the previous example, the code was error prone as it had no fallback values in case the --color CSS custom property did not exist. A fallback value could be implemented like this, in which a fallback value must be included every time the --color is used ⬇️ :</p><pre>button {<br> --color: black;<br> border: .1em solid var(--color, black);<br> color: var(--color, black);<br>}</pre><pre>button.pink {<br> --color: pink;<br>}</pre><p>Instead, the fallback value can be included <em>once</em> in a <em>private </em>CSS custom property called --_color ⬇️ , and thereby making the code more readable:</p><pre>button {<br> --_color: var(--color, black);<br> border: .1em solid var(--_color);<br> color: var(--_color);<br>}</pre><pre>button.pink {<br> --color: pink;<br>}</pre><h3>Takeaway #3: CSS Variables allow us to create a higher level styling API</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=785">13:05</a>)</p><p>What Lea means by this, is that by utilising CSS custom properties, we are able to produce components that are more encapsulated in terms of styling than before. The CSS custom properties can be seen as a new styling API of a component that we can interact with. When utilised right, we can provide components that we can change the internal implementation of without breaking already written code.</p><p>Let’s say the design spec changes. Previously, the hover effect of a button was a background change ⬇️ :</p><pre>button {<br> --_color: var(--color, black);<br> border: .1em solid var(--_color);<br> color: var(--_color);<br>}</pre><pre>button:hover {<br> background: var(--_color);<br> color: white;<br>}</pre><pre>button.pink {<br> --color: pink;<br>}</pre><p>It should now instead get a box-shadow effect on hover. The only change would be to change the background declaration to box-shadow: 0 0 0 1em var(--_color) inset;, one line of code change ⬇️ :</p><pre>button {<br> --_color: var(--color, black);<br> border: .1em solid var(--_color);<br> color: var(--_color);<br>}</pre><pre>button:hover {<br> box-shadow: 0 0 0 1em var(--_color) inset; /* Updated */<br> color: white;<br>}</pre><pre>button.pink {<br> --color: pink;<br>}</pre><p>On the other hand, if the variations of the component was implemented as below, without the use of CSS custom properties, the implementation would break if one forgot to change the line of code not only one place, but multiple ones ⬇️ :</p><pre>button {<br> border: .1em solid black;<br> color: black;<br>}</pre><pre>button:hover {<br> box-shadow: 0 0 0 1em black inset; /* Updated */<br> color: white;<br>}</pre><pre>button.pink {<br> border: .1em solid pink;<br> color: pink;<br>}</pre><pre>button.pink:hover {<br> background: pink; /* This place also need to be updated */<br>}</pre><h3>Takeaway #4: CSS variables cannot be interpolated unless we register them with @property</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=989">16:29</a>)</p><p>Using the following lines of code, the buttons color hue would just go straight from 0 to 180 degrees after 5 seconds ⬇️ :</p><pre>@keyframes color-hue {<br> from { --color-hue: 0; }<br> to { --color-hue: 180; }<br>}</pre><pre>button.rainbow {<br> --color: hsl(var(--color-hue) 60% 50%)<br> animation 5s color-hue linear infinite;<br>}</pre><p>… unless we include a @property registration for the --color-hue CSS custom property. This allows a CSS custom property to animate nicely throughout keyframes, in this case making the button’s --color property animate halfway through the color hue wheel in 5 seconds ⬇️ :</p><pre>@property --color-hue {<br> syntax: &quot;&lt;number&gt;&quot;;<br> initial-value: 0;<br> inherits: true;<br>}</pre><pre>@keyframes color-hue {<br> from { --color-hue: 0; }<br> to { --color-hue: 180; }<br>}</pre><pre>button.rainbow {<br> --color: hsl(var(--color-hue) 60% 50%)<br> animation 5s color-hue linear infinite;<br>}</pre><p>One can also register a CSS custom property in JavaScript using CSS.registerProperty() . Lea mentions a few reason when this option can be used, and that is either a) when multiple similar CSS custom properties needs registration, or b) for debugging reasons, as there is little feedback using the @property syntax if something does not work, and the JavaScript API gives nice readable error messages.</p><h3>Takeaway #5: @property-defined initial values take precedence over var() fallback</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=1162">19:20</a>)</p><p>Lea mentions this as one has to be aware of that if one registers a custom property for instance due to the need of it being interpolatable, you automatically need to give it an initial value. All three descriptors syntax , initial-value and inherits are mandatory when registering a CSS custom property (only exception is that we can omit the initial-value descriptor if the syntax is a wild card).</p><p>If an initial-value for a CSS custom property is defined (meaning it as been registered using the @property), the entire use case for pseudo private variables to provide a fallback value efficiently is eliminated. A fallback value in var() will never apply, the initial-value always takes precedence.</p><p>However, the use case for pseudo private variables is not entirely eliminated. Registering a CSS custom property using the @property in your stylesheet will make the CSS custom property globally scoped. Sometimes that is not desirable. For instance, sometimes one can use fairly generic CSS custom property names like--color that should be locally scoped to a component, and in that use case, one might not want its value to fallback to some globally initial color. The only way to get a registration of a CSS custom property to be locally scoped, if its registration happens in the shadow tree, then it will be scoped to the shadow tree.</p><p>Thus, there are use cases for either, for registering a property globally, or rather giving it a fallback value with the var() syntax/using a pseudo private variable. There is one small caveat here though. If<em> </em>@property is not supported, the var fallback in var() will actually apply regardless.</p><h3>Takeaway #6: Use variables for pure data, not CSS values</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2292">38:12</a>)</p><p>In CSS today, you can give a CSS custom property a unit by multiplying it using calc ⬇️ :</p><pre>/* Number to unit */<br>height: calc(var(--foo) * 1%);<br>width: calc(var(--foo) * 1px);</pre><p>However, there is no way in CSS today to possibly obtain the numeric value from a CSS custom property if the property is already defined with a unit. For this reason, Lea’s advice is to keep the values of CSS custom properties pure, and without unit. This is especially important if the value comes from JavaScript, because if a different unit is needed in CSS, you don’t need to go to your JavaScript to change units.</p><pre>/* Unit to number, not possible! */<br>--foo: 42px; /* There is no way to get the value 42 from this var */</pre><p>One small additional detail, in the future, also number to unit conversion should be possible by using calc with division: calc(var(--foo) / 1%) ;</p><h3>Takeaway #7: content only accepts strings. You can convert numbers to strings via counter-reset</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2394">39:54</a>)</p><p>This takeaway combines with the previous one. The idea Lea wants to show in her example how should be done, is how to be able to output the value of a CSS custom property on the web page.</p><p>The example she uses is to get a bar chart to display the percentage of each column, with the percentage of each column given using a CSS custom property ⬇️ :</p><pre>&lt;div class=&quot;bar-chart&quot;&gt;<br> &lt;div style=&quot;--p: 26&quot;&gt;Column 1&lt;/div&gt;<br> &lt;div style=&quot;--p: 100&quot;&gt;Column 2&lt;/div&gt;<br> ...<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJ2DAJttAG6dWi3UK3RHww.png" /><figcaption>This is the result Lea want to obtain in her demonstration on how to get the value of a CSS custom property displayed on the web page. (Source: <a href="https://youtu.be/ZuZizqDF4q8?t=2130">Youtube video</a>)</figcaption></figure><p>This will unfortunately not be possible with the following lines of code ⬇️ :</p><pre>.bar-chart &gt; div {<br> /* Number to unit conversion */<br> height: calc(var(--p) * 1%;<br>}</pre><pre>.bar-chart &gt; div::before {<br> /* This will not work */<br> content: var(--p);<br>}</pre><p>It does not work because the CSS property content only accepts strings. You can however convert number to strings using the CSS property counter-reset , making these lines of code work ⬇️ :</p><pre>.bar-chart &gt; div::before {<br> counter-reset: p var(--p);<br> content: counter(p) &quot;%&quot;;<br>}</pre><h3>Takeaway #8: … but you can only convert integers</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2437">40:37</a>)</p><p>Again, following up the previous takeaway, the numbers that can be converted using counter-reset can only be <em>intergers</em>, thus, the bar-chart example would not work for the following column, it would just get output 0% ⬇️ :</p><pre>&lt;div class=&quot;bar-chart&quot;&gt;<br> ...<br> &lt;div style=&quot;--p: 81.25&quot;&gt;Column X&lt;/div&gt;<br> ...<br>&lt;/div&gt;</pre><h3>Takeaway #9: Convert a number to an integer by assigning it to a property registered as “&lt;integer&gt;” inside calc()</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2516">41:56</a>)</p><p>But, of course Lea does not accept this defeat. We need to be able to convert the float number we are receiving to an integer. By utilising the @propertysyntax, and also wrapping the original number/CSS custom property in calc(), we can convert the number to an integer. Lea credits <a href="https://twitter.com/anatudor/status/1399849494628425734">Ana Tudor</a> for figuring out this integer casting trick in CSS ⬇️ :</p><pre>@property --integer {<br> syntax: &quot;&lt;integer&gt;&quot;;<br> initial-value: 0;<br> inherits: true;<br>}</pre><pre>...</pre><pre>.bar-chart &gt; div::before {<br> --integer: calc(var(--p));<br> counter-reset: p var(--integer);<br> content: counter(p) &quot;%&quot;;<br>}</pre><p>And this is how you control the conversion:</p><pre>/* Round: */<br>--integer: calc(var(--number));</pre><pre>/* Floor: */<br>--integer: calc(var(--number) - 0.5);</pre><pre>/* Ceil: */<br>--integer: calc(var(--number) + 0.5);</pre><p>For reference, it is actually planned for the future of CSS, that it will provide rounding functions. And she also claims that for the even further future of CSS, we won’t hopefully not even need the counter-reset trick for text conversion of CSS custom properties, we will even get a text() function that will convert any value to a string️, the console.log() of CSS she compares it to ⬇️ :</p><pre>/* Future CSS */<br>/* Round: */<br>counter-reset: p round(var(--p), 1);</pre><pre>/* Floor: */<br>counter-reset: p round(down, var(--p), 1);</pre><pre>/* Ceil: */<br>counter-reset: p round(up, var(--p), 1);<br></pre><pre>/* Even further future CSS */<br>content: text(var(--p)) &quot;%&quot;;</pre><h3>Takeaway #10: CSS variable conditionals</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2749">45:49</a>)</p><p>Continuing on the same example with the bar chart, it is also desirable to make the color of each column of the bar-chart depend on the percentage it represents. Deciding on a range, it means that we want the color of a close to 0% column be yellow, but the column of a close to a 100% column be blue, making the columns interpolate the hue of the color wheel, and also slightly change the lightness of the column.</p><p>This is a special case of CSS variable conditionals that is called a <em>linear mapping —</em> we want to map a number into a representative number in an other number space (i.e. x ∈ [x1, x2] → y ∈ [y1,y2], to remind myself about the happy times, being able to use mathematical notation when in university 😍). Lea even made a webpage to not having to remember the formula for achieving this every time, <a href="https://css.land/ranges/">css.land/ranges</a>. The formula has to be implemented something like this in CSS ⬇️ :</p><pre>--y: calc((((var(--x) - x1) * (y2 - y1)) / (x2 - x1)) + y1);</pre><h3>Takeaway #11: Linear mapping allows the same variable to control multiple things, continuously or discretely</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2832">47:12</a>)</p><p>Lea continues on her topic on linear mappings, by showing us how the linear mapping function gets even more simplified when used in a discrete setting, more precisely to create conditionals, meaning when one simply want one value of a CSS property, or another. We want to control this with a CSS custom property that either has a value of 0 (off), or a value of 1 (on), basically a ternary expression. When the range does not matter, the formula gets simplified to what is shown in the code block below. However, since the calc() function is still required, it is important to remember that this trick for creating conditionals only applies as a solution for setting values for CSS properties that take on numerical values, like line-height️ for example ⬇️ :</p><pre>--is-true: 1;<br>--is-not-true: calc(1 - var(--is-true);</pre><pre>-property: calc(var(--is-true) * value_if_true + var(--is-not-true) * value_if_false);</pre><pre>// Example for how to change the line-height for a glossy button:<br>line-height: calc(var(--glossy) * 1.1 + var(--not-glossy) * 1.5);</pre><h4>Logical operators</h4><p>The trick for creating conditionals for values of numerical CSS properties above, utilises how CSS custom properties can be used to create logical operators. In the example above, the not operator was utilised. Lea shows how boolean algebra can be applied in CSS to create two additional logical operators, the or and and operator⬇️ :</p><pre>--not-a: calc(1 - var(--a));<br>--a-or-b: min(var(--a) + var(--b), 1);<br>--a-and-b: calc(var(--a) * var(--b));</pre><h4>Space Toggles</h4><p>(The subject of space toggle is explained in the<a href="https://youtu.be/ZuZizqDF4q8?t=1206"> video from around 20:05</a>.)</p><p>Earlier in her talk, Lea presented the concept of <em>space toggles</em>, as a mean for creating conditionals. The way of using linear mappings to achieve this is a simplified, more readable solution she claims. However, linear mappings to create conditionals are limited to CSS properties that take on numerical values only (as previously stated), whereas space toggles are not. Space toggles can be used for creating conditionals for the background or box-shadow property too for instance. It is a more powerful tool, although it perhaps provides a less readable solution for creating conditionals for numerical values in CSS, it is still included in this article, as it is a tool that makes us able to solve a bigger set of the problems than the linear mapping function for creating conditionals allows us to.</p><p>Lea starts off her explanation of the concept space toggles by giving her thoughts about CSS variables as an API. In that context, she brings up the fact that the W3C in their <a href="https://www.w3.org/2001/tag/doc/webcomponents-design-guidelines/">guidelines for creating web platform compatible components </a>actually advises <em>against</em> using custom attributes for styling. The reason why developers do it regardless, is that there is yet a way to achieve conditionals in CSS.</p><blockquote>Don’t use custom attributes for styling, like <em>bgcolor</em>. Instead use Custom Properties or CSS Shadow Parts. — in <a href="https://www.w3.org/2001/tag/doc/webcomponents-design-guidelines/#native-html-elements">1.1.4 Guidelines for creating web platform compatible components by W3C</a></blockquote><p>To give an example, this is for instance how the component library <a href="https://shoelace.style/">Shoelace</a> utilises what Lea claims is an anti-pattern to achieve an outlined button, by introducing a custom attribute tag outline ⬇️ :</p><pre>&lt;sl-button variant=&quot;default&quot; outline&gt;Default&lt;/sl-button&gt;</pre><p>In the future, CSS will provide <em>style container queries</em>, which are described in greater detail by Una Kravitz in her article <a href="https://una.im/style-queries/">Style Queries</a>, and it will look something like this ⬇️ :</p><pre>/* Future CSS */<br>@container style(--glossy:on) {<br> button {<br>  box-shadow: 0 .1em hsl(0 0% 100% / .4) inset;<br> }<br>}</pre><p>However, since the future has yet to come, Lea demonstrates how we can fake this behaviour with what she calls <em>space toggles</em>. It looks something like this ⬇️ :</p><pre>:root {<br> --ON: initial;<br> --OFF: ; /* value is a white space */</pre><pre>button:nth-child(even) {<br> --glossy: var(--ON);<br>}</pre><pre>button {<br> background: var(--glossy, linear-gradient(hsl(0 0% 100% / .4), transparent) pink;<br> box-shadow: var(--glossy, 0 .1em hsl(0 0% 100% / .4) inset);<br> border: var(--glossy, .05em solid pink);<br>}</pre><p>To explain what is happening her, this idea was born after the realization that <em>white space</em> is in fact a perfectly valid property value: --foo: ; . So to turn something <em>off</em>, we make a var() statement that will just be evaluated as a white space, and then providing the value we want when opting <em>out</em> (in this case just a plain background, pink, and no linear-gradient) <em>after</em> the var() statement, like: var(--foo, linear-gradient(..)) pink. This works since white-spaces are stripped away during evaluation time in CSS, leaving it to become: background: pink;</p><p>To turn something <em>on, </em>the initial value is used instead of a whitespace, as the initial value works as if the CSS custom property was never given a value, making the fallback in the var statement kick in. This is what is described in the following code block ⬇️ :</p><pre>/* White space is a valid value, so the fallback does not kick in */<br>.off {<br> --foo: ; /* Value is a white space */<br> background: var(--foo, linear-gradient(white, transparent)) pink;<br>}</pre><pre>/* initial triggers the fallback, as if the variable had no value */<br>.on {<br> --foo: initial;<br> background: var(--foo, linear-gradient(white, transparent)) pink;<br>}</pre><p>Some more details of this solution needs to be pointed out in order to understand the full picture of how this works. One of those points, is the concept of Invalid At Computed Value Time (IACVT) needs to be explained (explained in the <a href="https://youtu.be/ZuZizqDF4q8?t=1577">video from around 26:17</a>). It had to be invented to make CSS custom properties possible, Lea tells. IACVT happens when you provide a CSS property with a value that is not valid. Usually, the browser throws away lines of code it does not understand, but because all other possibly given fallbacks are thrown away by the browser ahead of the time of computation where the value is discovered to be invalid, the value is instead substituted to the value unset . Unset sets inherited properties to the inherit keyword, and non-inherited properties get the initial keyword (the closest thing we have to a reset keyword in CSS, Lea says) ⬇️ :</p><pre>--foo: 42deg;<br>/* This declaration is invalid at computed value time (IACVT) */<br>background: var(--foo); /* It is treated as background: unset; */</pre><p>This is the case for the border of the button in this example. Without declaring the border at all, the button would get the default border the browser provides. However, since the declaration border: var(--glossy, .05em solid pink); is evaluated as IACVT when --glossy has the value of a white space, the border is treated as border: initial; , and the initial value sets the border-style to none which means that the border is removed.</p><p>Also the line-height value of this example is a bit complex, because what we what in this example is a conditional. If not <em>glossy</em>, we want a line-height of 1.5, but if <em>glossy</em>, it should be a value of 1.1. This is achieved by using the space toggle in a calc() to trigger computation. When the space toggle is a white space, only calc(1.5) will remain in the expression, but if the space toggle has the value initial , the fallback will trigger, resulting in: calc(1.5 — .4)️ ⬇️ :</p><pre>/* Space toggle version for numerical values */<br>line-height: calc(1.5 var(--glossy, - .4));</pre><pre>/* Fictional (future?) syntax, a ternary expression */<br>line-height: if(--glossy = initial, 1.1, 1.5);</pre><pre>// However, simplified version, using linear mapping for conditionals<br>line-height: calc(var(--glossy) * 1.1 + var(--not-glossy) * 1.5);</pre><p>Lastly, it should not be expected that web developer that does not enjoy getting CSS-deep should remember that the white space value means <em>off, </em>and that the initial value means <em>on. </em>To abstract this detail away and create a nice API to work with, we introduce the --ON and --OFF CSS custom properties on :root that will have the values initial and ; (white space), respectively ⬇️ :</p><pre>:root {<br> --ON: initial;<br> --OFF: ; /* white space is a valid value */<br>}</pre><p>Space toggles can also be used to provide progressive enhancement in browsers that support a feature that others don’t, for instance different color spaces. This is explained in detail in the <a href="https://youtu.be/ZuZizqDF4q8?t=2029">video from around 33.49</a>, and left out of this article as it is just a further exploitation of the concept that has already been explained.</p><h3>Takeaway #12: Range mapping allows you to decouple input from output</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=2967">49:27</a>)</p><p>For this takeaway, Lea uses a svg illustrated in the image underneath ⬇️, in which the location of the eyes are supposed to be controlled by the location of the user’s mouse pointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYjJ-TfmOXCpZYr-jtG_0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLmg1t_lPjLdDYB1s8lobw.png" /><figcaption>Lea produces an example in which the location of the eyes in an svg is controlled by the user’s mouse pointer. In the top image the mouse is to the left of the svg, in the bottom image, it is centered on screen.</figcaption></figure><p>However, they are controlled by a horizontal center, the cx css property, which gives the desired position of the eyes between 25-75-px. However, Lea desires to improve this API of the eye positioning, by making the input parameter for positioning more intuitive, and in addition make this input value less dependent on the CSS, so it would not have to change if other CSS properties changed value.</p><p>She introduces a CSS custom property--look that she want to control the eye positioning with, and by letting it’s range [0,1] map to the pixel range of the eye positioning, she decouples the input from the output values:</p><pre>.iris {<br>   --look: .5;<br>  cx: calc(25px + 50px * var(--look));<br>}</pre><h3>Takeaway #13: Relative values inherit as syntax token unless the property is registered</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=3117">51:57</a>)</p><p>To illustrate this takeaway, Lea creates something like this online — a little emoji with a speech bubble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*gXXS0nljcETkmvrU-LtpLQ.png" /><figcaption>The code snippet below creates this element.</figcaption></figure><p>The code snippet below shows the most important code for creating this speech bubble example that gets her point across. The “pointer” refers to the little triangle above the emoji’s head. She shows us that without registering the css custom property, the following bug occurs when trying to resize the emoji:</p><ul><li><em>Without </em>registering the css custom property --pointer-size , when changing the emoji-sizeto e.g. 3em, the font-size of the after pseudo-element becomes 3em, and since the font-size property defines the size of an em in an element, and the margin-top that is set to 1em becomes 3 times as large as it originally was.</li><li>However, if registrering the property--pointer-height as showed in the example below <em>as a length</em>, what is inherited in the after pseudo-element is no longer what is called the <em>syntax token</em> 1em. The browser instead interprets it as length, which ensures that it is <em>the actual length </em>that is inherited, the pixel value as it is calculated in the .speech-bubble element where it is defined.</li></ul><pre>/*<br>   Registring the css custom property makes the inherited value become<br>   the calculated one.<br>   In this case, it would ensure --pointer-height resolving to for example <br>   16px, and not 1em.<br>*/<br>@property --pointer-height {<br>   syntax: &#39;&lt;length&gt;&#39;<br>}<br><br>.speech-bubble {<br>   ...css declarations<br>   --pointer-width: 1em;<br>   --pointer-height: 1em;<br>   --pointer-offset: 1.5em;<br>   --emoji: &#39;😄&#39;;<br>   --emoji-size: 2em<br>}<br><br>/* The pointer: */<br>.speech-bubble::before { <br>   width: var(--pointer-width);<br>   height: var(--pointer-height);<br>   right: var(--pointer-offset);<br>}<br><br>/* The emoji: */<br>.speech-bubble::after {<br>   content: var(--emoji);<br>   margin-top: var(--pointer-height);<br>   font-size: var(--size);<br>}</pre><h3>Takeaway #14: Registering a property as &lt;length&gt; allows us to pass down ancestor font sizes</h3><p>(<a href="https://youtu.be/ZuZizqDF4q8?t=3123">52:03</a>)</p><p>Another use case of takeaway #13, we can use this behaviour to pass down ancestor font sizes. Lea shows this using a html example with a group of options in which one can be selected, using the&lt;select&gt; and &lt;optgroup&gt; tags:</p><pre>&lt;select size=&quot;5&quot;&gt;<br>   &lt;option value=&quot;&quot;&gt;None&lt;/option&gt;<br>   &lt;optgroup&gt;<br>     &lt;option value=&quot;option1&quot;&gt;Option 1&lt;/option&gt;<br>     ... more options<br>   &lt;/optgroup&gt;<br>&lt;/select&gt;</pre><p>This HTML produces something like the leftmost lift below, a great gap between the selected value and the options. Lea want to improve the look of this &lt;select&gt; , by minimising this gap as showed in the rightmost image. The middle image shows how the select may up end looking when using the only solution (it is more of an hack) she was able to come up with before @property syntax was a reality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*EZ5gtpCsfd90T-B2mAwkng.png" /><figcaption><strong>Leftmost image:</strong> How a &lt;section&gt; with an &lt;optgroup&gt; and &lt;option&gt; tags look like natively in the browser. <strong>Middle image:</strong> How it may end up looking when trying to minimise the gap between the selected option and the options that can be selected without<strong> </strong>using the @property syntax. <strong>Rightmost image:</strong> Lea is able to minimise the gap and<strong> </strong>use the same font-size for the selected value and the options when using a css custom property that she registers using the @property syntax.</figcaption></figure><p>Before the @property syntax was supported in CSS, the <em>only </em>solution she was able to find, was to set the font-size value of the &lt;optgroup&gt; to zero, then setting the font-size of all its children. But, then the font-size may end up looking differently betweent the selected option and the options, as shown in the middle image above.</p><pre>/* The ugly hack: */<br>optgroup {<br>   font-size: 0<br>}<br><br>opt-group &gt; * {<br>   /* <br>      Ideally, we want to set it back to the parent font-size,<br>      but we don&#39;t have any reference to it, so making our best guess.<br>   */<br>   font-size: 1rem; <br>}</pre><p>If we instead save the select tag’s font-size value (which resolves to 1em in every element) in a css custom property, we are able to produce the look in the rightmost image above, in which the selected option and the options have the same font-size :</p><pre>/* Instead passing down ancestor font-sizes: */<br>/* <br>   NB: Without registering --parent-em, --parent-em would resolve to <br>   it&#39;s direct parent&#39;s font-size, which is 0.<br>*/<br>@property --parent-em {<br>   syntax: &quot;&lt;length&gt;&quot;;<br>   initial-value: 0;<br>   inherits: true;<br>}<br><br>select {<br>   ---parent-em: 1em;<br>}<br><br>optgroup {<br>   font-size: 0<br>}<br><br>opt-group &gt; * {<br>   font-size: var(--parent-em);   <br>}</pre><p>What is important when using this trick, is that in the case of lacking browser support for the @property syntax (which usually only results in a slightly less refined result on the web page), the options would would actually no longer show, since the inherited font-size becomes zero. This is because the support for @property is actually much less than for CSS custom properties, which can be seen in the image below. Still to this day (Jan 2023), Safari and Firefox which at the time of the video had a marked share of ~30%, have still yet to implement support for the @property syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJ0wNvUttb4oK1ZFNXPfrA.png" /><figcaption>Showing that the browser support for @property and CSS.registerProperty() still lacks in the Safari browser and the Firefox browser. (Source: <a href="https://youtu.be/ZuZizqDF4q8?t=3260">YouTube video</a>)</figcaption></figure><p>For this reason, it is <em>very</em> important in this case to implement a correct fallback. This can be done by detecting @property support using the following code snippet adding a class to root, and then add it as a descendent where ever needed:</p><pre>if(window.CSSPropertyRule) {<br>   let root = document.documentElement;<br>   root.classList.add(&quot;supports-at-property&quot;)<br>}<br><br>/* How to use it in CSS: */<br>.supports-at-property optgroup {<br>   font-size: 0;<br>}</pre><p>However, would it not be great if we instead could just detect @property syntax in CSS alone? Unfortunately, the @supports syntax can not be used directly as outlined in the code block below:</p><pre>/* <br>   Leveraging this syntax would be great to detect @property support, <br>   but it is unfortuneately not possible.<br>*/<br>@supports (???) {<br>   optgroup {<br>      font-size: 0;<br>   }<br>}</pre><p>Lea’s first inclination was that perhaps it would be possible to detect the invalidity of a css custom property. By first registering it, and then assigning something invalid to it, she hoped one would be able to produce a fallback, here illustrated by registering a color property, then giving it the value of 0:</p><pre>/* Failed attempt for detecting lacking @property support in CSS: */<br>@property --color-test {<br>   syntax: &quot;&lt;color&gt;&quot;;<br>   initial-value: transparent;<br>   inherits: true;<br>}<br><br>@supports {--color-test:0) {<br>   /* Does not support @property */<br>   :root {<br>      background:red;<br>   }<br>}</pre><p>The reason the code block above fails as a mechanism for detecting lacking @property support in CSS in a browser, is:</p><blockquote><em>“The syntax of registered properties is only checked at computed value time” — Lea Verou (</em><a href="https://youtu.be/ZuZizqDF4q8?t=3327"><em>YouTube, 55:27</em></a><em>)</em></blockquote><p>This means it is <em>not</em> checked at parsed time. This makes sense because for traditional CSS properties, the value would not change, but for css custom properties, the value of it can change any time. Instead, we can leverage inheritance to detect @property support in CSS, by registering a CSS custom property (in this case--no-at-property-fallback ) with inherits: false , set it to a value at an ancestor and combine it with a fallback as shown ⬇️. In the example below, the background only becomes green <em>if </em>the @property syntax is <em>not </em>supported.</p><pre>/* <br>   Leveraging that Safari and Firefox browsers still support CSS custom <br>   properties, but not the @property. <br>   This makes the --no-at-property-fallback property only inherited in those <br>   browsers, which can be used to produce a fallback (red background color).<br>*/<br>@property --no-at-property-fallback {<br>   syntax: &quot;*&quot;;<br>   inherits: false;<br>}<br><br>:root {<br>   /* Will only inherit if @property is ignored */<br>   --no-at-property-fallback: red;<br>}<br><br>body {<br>   background: var(--no-at-property-fallback, green)<br>}</pre><p>In the exact use case of inheriting a parent font-size , it would look like this (not tested, and Lea did not show this in her talk, but I <em>think</em> it would look like this 🙃):</p><pre>@property --parent-em {<br>   syntax: &quot;&lt;length&gt;&quot;;<br>   initial-value: 0;<br>   inherits: true;<br>}<br><br>@property --no-at-property-fallback {<br>   syntax: &quot;*&quot;;<br>   inherits: false;<br>}<br><br>select {<br>   ---parent-em: 1em;<br>}<br><br>optgroup {<br>   --no-at-property-fallback: 1rem;<br>   font-size: 0:<br>}<br><br>opt-group &gt; * {<br>   font-size: var(--no-at-property-fallback, var(--parent-em));   <br>}</pre><h3>Summary</h3><p>Lea ends her talks with asking if these tricks she just showed are just hacks that should be avoided. Her reasoning around that subject, is that she thinks one should always prioritize API simplicity over implementation simplicity. The reason? The internal implementation can always be rewritten when native CSS support is available for that functionality, and also, the API is used a lot more and is thus more difficult to change when the implementation is done. She claims that the hacks she showed in this talk when precisely in the implementation.</p><blockquote>You got to do what you got to do to expose a nice API — Lea Verou</blockquote><p>Here are the takeaways summarized:</p><ol><li><strong>CSS variables are just regular variables</strong></li><li><strong>Pseudo-private variables succinctly reduce fallback duplication</strong></li><li><strong>CSS Variables allow us to create a higher level styling API</strong></li><li><strong>CSS variables cannot be interpolated unless we register them with </strong><a href="http://twitter.com/property"><strong>@property</strong></a></li><li><a href="http://twitter.com/property"><strong>@property</strong></a><strong>-defined initial values take precedence over var() fallback</strong></li><li><strong>Use variables for pure data, not CSS values</strong></li><li><strong>Content only accepts strings. You can convert numbers to strings via counter-reset</strong></li><li><strong>… but you can only convert integers</strong></li><li><strong>Convert a number to an integer by assigning it to a property registered as “&lt;integer&gt;” inside calc()</strong></li><li><strong>CSS variable conditionals</strong></li><li><strong>Linear mapping allows the same variable to control multiple things, continuously or discretely</strong></li><li><strong>Range mapping allows you to decouple input from output</strong></li><li><strong>Relative values inherit as syntax token unless the property is registered</strong></li><li><strong>Registering a property as &lt;length&gt; allows us to pass down ancestor font sizes</strong></li></ol><h3>Lea’s motivation for the talk</h3><p>I know this topic may occur a bit out of order, but I wanted to skip right to the good stuff/what one usually is searching for in a YouTube video in this article. However, I wanted to include this bit too, as I found it really interesting. It teaches one a bit how the development of the web is looked after.</p><p>Lea starts of her <a href="https://www.youtube.com/watch?v=ZuZizqDF4q8">talk</a> with explaining the motivation behind it. In 2020, she was the lead of the css chapter for the <a href="https://almanac.httparchive.org/">Web Almanac</a>, which is the <a href="https://httparchive.org/">HTTP Archive’s</a> annual state of the web report. It reveals how developers currently are utilising the available web technologies.</p><p>Lea was surprised to see that developers were currently still using css custom properties first and foremost in a basic way, on a surface level, still not taking advantage of it in higher potential use cases, even though the css custom properties has been available to developers more than 5 years ago (<a href="https://caniuse.com/css-variables">from around 2016</a>). This can be explained by introducing the term <em>variable depth</em>, which is how many variable references do you have to look up in order to obtain the current value.</p><p>In 2020, more than 60% of the css custom properties uses in 2020 was on variable depth <strong>zero</strong>, which means just declaring the css custom property as shown below ⬇️:</p><pre>... {<br> /* variable depth zero */<br> --hue: 360;<br>}</pre><p>Also, most css custom properties were declared on the :root level, which essentially means utilised as just constants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clBJhCpBCSKAzryyhbYf_Q.png" /><figcaption>Most css custom properties were declared on the :root level in 2020. (Source: <a href="https://youtu.be/ZuZizqDF4q8?t=290">YouTube video</a>)</figcaption></figure><p>Lea’s thoughts on this, is that we have this awesome opportunities to use css custom properties more as reactive properties, and not just as constants (andthe reason for <em>why</em> this is the main perception, is that it was evangelised that you with css custom properties you <em>finally</em> have reusable colors and fonts). In her <a href="https://www.youtube.com/watch?v=ZuZizqDF4q8">talk</a>, she shows us <em>how</em> to use css custom properties as reactive properties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d281218de60a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to (Learn to) Implement Images on the Web (2021)]]></title>
            <link>https://forsethingvild.medium.com/how-to-learn-to-do-images-on-the-web-2021-14cd2e083e5?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/14cd2e083e5</guid>
            <category><![CDATA[responsive-images]]></category>
            <category><![CDATA[mat-marquis]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[image-compression]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Wed, 26 May 2021 10:17:08 GMT</pubDate>
            <atom:updated>2021-12-07T08:45:12.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Images are the biggest assets that gets shipped with a web page according to <a href="https://youtu.be/F1kYBnY6mwg?t=48">these smarty pants</a> (developer advocates for Google Chrome, my heros ❤), see the quote below.</p><blockquote>50% of the bytes that go over the wire for any given page are on average images [from studies across web pages, as of 2020]— <a href="https://www.youtube.com/watch?v=F1kYBnY6mwg&amp;t=48s">Suma</a></blockquote><p>As a frontend developer, you should learn the tricks on how to make images impact the users’ bandwidth as little as possible and the user experience as much as possible. It’s the polite thing do, right?</p><p>However, there is a jungle out there. A jungle of internet resources on how to do things, on image formats, and which image formats are outdated and which are new? And even — which of the new ones should actually not be used? Puh!</p><p>So I hope I can be your Bagheera on this journey, showing you the way. In this article, I summarize the resources that helped <em>me</em> feel up to speed and knowledgeable on the subject. The article ends with a conclusion on the top greatest tips for images on the web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KjCCzUfYDf8aO7RI.jpg" /><figcaption>Let’s go on a “images on the web” journey. (Source: <a href="https://www.moviehousememories.com/the-jungle-book-1967-summary/">https://www.moviehousememories.com/the-jungle-book-1967-summary/</a>)</figcaption></figure><h3>Understand The Different Image Formats</h3><p>The first thing you should do, is to understand the different image formats. <em>Different image formats are suited for different kind of images. </em>For this purpose, I’ll direct you to the same video as above, the “Image Compression Deep Dive” video from Google Chrome developer advocates <a href="https://twitter.com/jaffathecake?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Jake Archibald </a>and <a href="https://twitter.com/DasSurma?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Surma</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FF1kYBnY6mwg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DF1kYBnY6mwg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FF1kYBnY6mwg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eaa9f31d819bf6a346744f8f6a47797/href">https://medium.com/media/1eaa9f31d819bf6a346744f8f6a47797/href</a></iframe><p>Here are the key point (whenever you are in the need for a quick look-up of the video, without having to see it all over again):</p><ul><li>Usually, images used on the web have not compressed. For random images on the web, you are usually able <em>to half the size of the image file</em> <em>without losing much of the visual fidelity</em> by re-compressing it. (<a href="https://youtu.be/F1kYBnY6mwg?t=65">Jake Archibald 01:05</a>)</li><li>In a compression process, you are left to decide between different formats, different encoders, and you can also decide the settings within a particular encoder (the last one requires taking the level of expertise up a notch 😊). However, often people don’t optimize their images at all, so a huge performance gain can usually be achieved by just using default settings of an encoder and without going deep into the settings of encoders.</li><li>Below is the overview over the different the image formats categorized, and what each format spend their bytes on/are not good at. Each category offers a multitude of codecs, and you can try them all out in the <a href="https://squoosh.app/">Squoosh app</a> that Jake Archibald and his team made.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*4By9uhxp01UdobvjyRBiMQ.png" /><figcaption>A categorization of the image formats by Google developers. Source: <a href="https://youtu.be/F1kYBnY6mwg?t=127">https://youtu.be/F1kYBnY6mwg?t=127</a> at 02:07.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*wqeLFBBHB2UCUV_Zh5dLJg.png" /><figcaption>The properties of an image you should consider when choosing image format when compressiong to keep the image size as small as possible. Source: <a href="https://youtu.be/F1kYBnY6mwg?t=250">https://youtu.be/F1kYBnY6mwg?t=250</a> at 04:10)</figcaption></figure><ul><li>If you don’t know which category your image falls into, try different codecs using the <a href="https://squoosh.app/">Squoosh app</a> (build by Jake Archibald and his team), and use your own eyes to evaluate which codec gives you the best result for the least amount of data.</li><li>Lossy codecs: <br>They use <em>chroma sub sampling</em>, which is to describe the image using brightness (luma) and two chroma/color changes to describe the image, in order to reduce the image size.<br>They also take advange of the fact that out human eyes are bad at detecting changes in high frequency, but good at detecting low frequency changes. They divide the image in 8px times 8px blocks, and instead of describing each of the pixels within each block, they describe each block as a set of frequencies. The details of this is definitely out of scope of this article, but Jake illustrates how this work at 10:10 in <a href="https://youtu.be/F1kYBnY6mwg?t=610">this video</a>, if you are curious.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*24nWYhBiKFGf4be4k1hcvw.png" /><figcaption>A visual representation of the frequencies used by lossy codecs (such as JPEG) to reconstruct shapes in an image. (<a href="https://youtu.be/F1kYBnY6mwg?t=589">Source</a>)</figcaption></figure><ul><li>Lossy image formats are not good at sharp lines with solid colors next to solid color.</li><li>About lossy codecs (at 12:40 in the <a href="https://youtu.be/F1kYBnY6mwg?t=760">video</a>): WebP is better than JPEG. Reasons: It can use a different size for the square when splitting the image up in blocks it will then compress, it can use a nearby square as the starting point for the next, and it can choose between 4 different mathematical conversions for each block, whereas JPEG can only use one. WebP also supports transparency, and in fact has a lossless codec too. But, the downside is, it is not supported in Safari.</li><li>More about lossy codecs: From 14:20 approximately in the <a href="https://youtu.be/F1kYBnY6mwg?t=860">video</a>, Jake shows how to use the <a href="https://squoosh.app/">Squoosh.app</a> to compress images (because it ): He goes through some advanced settings for the WebP encoder (<em>the</em> <em>alpha filter</em> and <em>the spatial noise shaping</em>), compares WebP to JPEG, and argues that the compressors included in <a href="https://squoosh.app/">Squoosh</a> are much better than the ones Photoshop offer.</li><li>About lossless images: Each pixel will be described by the <em>difference</em> to the surrounding pixels. But lossless encoders take more encoding time, because they have to iterate through which strategies at what point in the picture gives the smallest image. Again, the lossless WebP is the best, but it does not have Safari support, but PNG does.</li><li>About lossless codecs: Again, at around (24:00) in the <a href="https://youtu.be/F1kYBnY6mwg?t=1440">video</a>, Jake shows how to use the <a href="https://squoosh.app/">Squoosh</a> app for lossless compression.</li></ul><h3>But, AVIF is Coming/Is Here Already</h3><p>In September 2020, Jake Archibald wrote <a href="https://jakearchibald.com/2020/avif-has-landed/">this blog post</a>, acknowledging that the content of the image compression video above now was already outdated, because of the arrival of the new future image format <em>AVIF. (</em>Words of disclamation: I included above the video despite of this, as I believe it is important anyhow to understand the basics, which I think the “image compression deep dive” video above gives.)</p><p>Just read the Jake Archibald post on AVIF and get “wowed”. Here at the key takeaway points:</p><ul><li>AVIF is only supported by Chrome (from v85 and above), but you can use the &lt;picture&gt; tag to provide the client with a fallback. On <a href="https://caniuse.com/?search=avif">caniuse.com</a> you can keep track of when other browsers have gained to support for AVIF.</li><li>Pictures with both low and high frequency details: An acceptable AVIF image (in Jake’s opinion) is<em> half the size</em> of WebP, which again is half the size of JPEG (in total one fourth of the JPEG size then).</li><li>Flat illustrations (sharp edges, lots of solid colors): SVG off course is the natural choice here, and nonetheless, one would usually go for a <em>lossless</em> codec for these kind of images (to avoid destroying the edges, a high frequency detail). However, it is worth noting that <em>the AVIF image makes a very decent job</em>, 8.69kB compared to 16.3kB of the lossless PNG format (the traced SVG format ended up at 12.5kB), so it made <a href="https://twitter.com/jaffathecake">Jake</a> reconsider the kinds of images lossy codecs can be used to.</li><li>Heavy SVG images: Original SVG started at 82kB, then the optimized PNG ended up at 30kB. There are a number of shapes and filters involved in the picture (which takes a lot of the CPU to render), and that is why it is best to avoid the original SVG. <em>AVIF performs the best her</em>, lowering it to a 13kB image size, a reduction of more than 80%.</li><li>Illustration with gradients: Flat color and sharp lines usually points to a lossless compression as already discussed in bullet point 3. But, lossless formats usually struggle with gradients, so this is a tricky image to know what to expect. With some extra tweaking on the different codecs (disabling “chroma subsampling for the JPEG and AVI, choosing a “sharp YUV for the lossy WebP, read more about it in <a href="https://jakearchibald.com/2020/avif-has-landed/#illustration-with-gradients">Jake’s article</a>, section “Illustration with gradients”), <em>he ends up with AVIF performing the best </em>at 12kB (although some blurring, and changes to some shapes), but it is nearly half the size of the second best codec, which is the lossy WebP at 27kB.</li><li>Downside of the AVIF format: JPEG and WebP are able to render bits of pieces of the image (either in “passes” like JPEG, or from top to bottom, like WebP) so the users will se the progress of a slow image download, whereas the AVIF image either shows all or nothing. This makes AVIF most appropriate for smaller quick to load-images. (This can however be solved by the format if it would serve a lower quality “preview” version of the image at the start of the file.)</li><li>Encoding time is a thing when choosing codec. The AVIF format has an “effort” setting in <a href="https://squoosh.app/">the Squoosh app</a> that you can tweak for the AVIF format, with an encoding time of a couple of seconds on “effort 2”, but it can take up to 10 minutes to encode on effort level 10!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*LBvo4Mh3O2Ljka5m6DJu_Q.png" /><figcaption>The <a href="https://squoosh.app/">Squoosh</a> app has an effort level you can experiment with when compressing your image using the AVIF format.</figcaption></figure><ul><li>Image formats to come: JPEG-XL and WebPv2. Jake is trying to take the claims about JPEG-CL with a pinch of salt <a href="https://jakearchibald.com/2020/avif-has-landed/#what-about-jpeg-xl-and-webpv2">as he writes</a>, it will come with a lossless and a lossy compression. The lossless compression it will offer seems to be better the the WebPs at least, but the lossy compression is meant for high quality images (in the cases where you can expect the user to zoom into the images etc.), so it might not be able to compete with the AVIF format at the lossy compression. Details about the WebPv2 codec is yet to come.</li></ul><h3>Learn To Compress Images</h3><p>What is “good” enough quality when you compress your images? You don’t want to provide your users with “blocky” images where artifacts of the image have been warped due to the compression as the expense of a smaller image size. There is a fine line there that needs to be figured out, and here is how.</p><p>Again, I will refer you to the <a href="https://jakearchibald.com/2020/avif-has-landed/">“Avif has landed”</a> article by <a href="https://twitter.com/jaffathecake">Jake Archibald</a>. Here is his rule for “acceptable quality” for the <em>majority </em>of images on the web:</p><blockquote>If a user looks at the image in the context of the page, and it strikes them as ugly due to compression, then that level of compression is not acceptable. <em>But</em>, one tiny notch above that boundary is fine. — <a href="https://jakearchibald.com/2020/avif-has-landed/#what-is-acceptable-quality">Jake Archibald</a></blockquote><p>The technique he us used in the article is the following:</p><ol><li>He used <a href="https://squoosh.app/">the Squoosh app</a>.</li><li>Zoomed the image out to 50%, to optimize for high-density displays, in which a CSS pixel/software pixel would contain several <em>hardware pixels, </em>e.g. 4 for a 4k display (read more about that for instance <a href="https://juiceboxinteractive.com/blog/a-pixel-is-not-a-pixel-designing-for-a-new-generation-of-mobile-devices/#:~:text=A%20hardware%20pixel%20is%20an,is%20a%20unit%20of%20measurement.&amp;text=With%20Apple&#39;s%20Retina%20display%2C%20a,device%20pixel%20ratio%20is%202.">here</a>).</li><li>Used his human eyes for reference: Dragged the quality slider for the specific format down until it looked bad, then moved it back a little bit.<br>If the codec had an “effort” setting, he sat it to max (requires more encoding time though).</li></ol><p>Surely, manually compressing every images on you page is not a scalable process. If you need to automate the process, you can use this manual process to figure out the codec settings a couple representative images. Maybe add a bit of extra quality to be safe as Jake points out in his <a href="https://jakearchibald.com/2020/avif-has-landed/#what-is-acceptable-quality">article</a>, and then use those settings in the automation process. Also, surely, for people who really <em>knows</em> a lot about image compression and quality, this way of doing it would not suffice — but we are just interested in doing images on the web <em>a little better </em>:)</p><h3>Learn To Measure Web Page Performance</h3><p><a href="https://twitter.com/jaffathecake">Jake Archibald</a> has a great <a href="https://jakearchibald.com/2021/f1-perf-part-1/">article</a> where he investigates the performance of different websites, in which he also loosely sums up his methodology for measuring a web page’s performance in the section <a href="https://jakearchibald.com/2021/f1-perf-part-1/#possible-improvements">here</a>.</p><p>He will use the <a href="https://developer.chrome.com/docs/devtools/evaluate-performance/">Chrome DevTools Performance panel</a> during development to measure performance. Then, in production, one can use the web page <a href="https://www.webpagetest.org/">WebPageTest</a> to test it on low-end devices, as this is what the majority of people actually has.</p><p>In the article, he decided to test on a 5 year old phone (Moto G4) on a 3G connection, as he argues that a lot of people don’t want to or can’t afford a high-end phone. So to sum it up, you have to know your users and decide on what you think is a representative device for <em>most </em>of your users, and also <em>where</em> they typically would access your page, in order to decide the quality of internet connection.</p><p>The <a href="https://www.webpagetest.org/">WebPageTest</a> tool gives you measures like: How many seconds it takes the page to become interactive on the first load, and on the second load, and an overview on the order of the downloaded assets and how much time each of them took to download. You even get to see bits used for connection setup (so you can ensure you don’t pay the price of connection setup more than necessary), and also <em>when</em> the actual bytes of each asset is received and hence,<em> </em>claims the bandwidth of the user’s connection.</p><p>This overview is interesting to us in this regard (optimizing images on the web), because you make sure that any image are <em>not </em>downloaded before any more critical resources (like the CSS, which actually was the case for the <a href="https://www.scuderiaalphatauri.com/en/">Alpha Tauri</a> webpage he first investigated, using an img tag, and not a link tag, will prevent this), and maybe more important, in the overview you get to see the true download time of each image. In Jake’s experiment, he was able to reduce the image size of both the logo and the hero image <em>by 90%</em> by compression (using the <a href="https://squoosh.app/">Squoosh</a> app), and that leads to performance gains.</p><p>Also, a small tip at the end that also favors to the img tag: Inline SVG should be avoided, as it makes the size of the HTML and hence the time it takes to download, bigger. It also prevents the browser from downloading more critical assets (like the CSS), as the browser downloads the complete HTML before starting on the next thing to download in the markup. For instance, in the case of the first web page he investigates, the browser ends up using bandwidth on a logo that is on the bottom of the page, instead of starting on the css that will style what is about the fold. By using the &lt;img&gt; tag, you allow the browser to be smarter than this about its priorities.</p><h3>Learn To Use the Sizes Attribute</h3><p>Do yourself a favor and invest in the <a href="https://abookapart.com/products/image-performance">“Image Performance”</a> ebook (or print) by Mat Marquis and make it your encyclopedia for the responsive images standard on the web.</p><p>Mat Marquis was at the time the chair of the Responsive Issues Community Group (RICG). In the book, he explains how the group developed what is now the new responsive images standard on the web.</p><p>The book is from 2018, and he explains the topics and the process of work the group did in a quirky and funny way. Also, the book is only about 70 pages long, so you get a lot of knowledge for your time and your bucks.</p><p>First, he makes the case <em>why</em> images do damage due to their great file size. The first chapter is about image formats and compression (a nice way to learn about image formats in addition to the Google video discussed above). The second chapter is about responsive images.</p><p>It is mainly the implementation details in chapter two that I want you to take as the take away message from this book. According to Mat, “the term “responsive images” refers to any combinations of the following” (Mat Marquis. “Image Performance”. Apple Books. 2018):</p><ul><li>Art directions: <em>“requesting visually distinct source files at specific viewport sizes.”</em></li><li>Image types: <em>“requesting new image formats with responsible fallbacks.”</em></li><li>Display density: <em>“requesting image sources appropriate for high-density displays only when necessary.”</em></li><li>Flexible images: <em>“providing the browser with information about a set of image sources and how they’ll be used in a page’s layout, so it can make the most appropriate request for a user’s browsing context.”</em></li></ul><p>(Mat Marquis. “Image Performance”. Apple Books. 2018)</p><p>In the book, you learn how to account for all of them. All of the 4 use cases above can be solved with either the &lt;picture&gt; tag and/or the <em>sizes</em> attribute on the &lt;img&gt; tag (which is the result of the work the RICG did). Here follows some examples, which I believe sum up what I regard as the take away messages from the book:</p><ul><li>Use the picture tag to vary between alternatives of different screen sizes, for example serve a square full width image on a tablet, and a portrait on desktop, or to serve different image formats. Se the examples from Mat Marquis book below ⬇️</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*CVMU5D-dLvXI9rH_qpYUIg.png" /><figcaption>The &lt;picture&gt; tag lets you explicitly control which image is rendered on different screen sizes. It can be used to vary between different alternatives for an image to comply to different art directions, for example a square full width image on a tablet in portrait mode, and a different one when the tablet is in landscape mode. Image from: Mat Marquis. “Image Performance”. Apple Books. 2018.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*8rn9nOkEJYdpVkiNqAp-Bg.png" /><figcaption>Use the &lt;picture&gt; tag to serve different image formats. In that way, you provide the browsers that support it images in the latest and best formats, at the same time as you provide a fallback image in the browsers that don’t. Image from: Mat Marquis. “Image Performance”. Apple Books. 2018.</figcaption></figure><ul><li>Use the <em>sizes</em> attribute together with the <em>srcSet</em> attribute to tell the browser what image to render for different screen sizes to make sure you don’t download a bigger image than necessary.<br>In the <em>sizes</em> attribute, you write the expected image size for different screen sizes. In the example below, the value of the sizes attribute can be read as follows: <em>If the screen width is minimum 1200px large, the image will be 1200px. If the screen is less (than 1200px), it will be 100% of the viewport.<br></em>In the <em>srcSet</em> attribute, you write what kind of file should be downloaded for the different image sizes. The <em>w</em> represents the <em>real</em> width of the image, which can be found if you inspect the image file on your computer. Thus, the srcSet attribute in the example below can be read like this: <em>If the width of the the image to be displayed is supposed to be less than 400px, download and show the small.jpg file. If the width of the image to be shown should be between 400px and 800px, serve the medium.jpg file. It the width of the image should be between 800px and 1600px, show the large.jpg file, and if the width of the image to be rendered should be between 1600px and 2400px, show the x-large.jpg-file.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*pvydNO5U2KUmjrXlXph3XA.png" /><figcaption>By using the sizes attribute on the image tag, you inform the browser how much big the image is expected to be on your page. Through the srcSet attribute, you explicitly tell the browser which image to download for the different sizes/widths that the image is expected to fit in to. By leveraging these two attributes, you can make sure that the browser does not download an image that is bigger than necessary, and you will save the impact the images have on your users´ bandwidth when accessing your page (and overall reducing the total download time for your page). Image from: Mat Marquis. “Image Performance”. Apple Books. 2018.</figcaption></figure><ul><li>Also, remember this: If using min-width as the media query, you want the largest sources first, as the &lt;picture&gt; tag will chose the first source that passes the media query. If using max-width as the media query, it is the other way around, the smallest image first.</li></ul><p>The bullet points above are meant as just a quick reminder whenever necessary. A more extensive explanation about the subject can be found in the <a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images">Responsive images</a> article on MDN, and specifically, more on how to read the <em>sizes</em> and the <em>srcSet</em> attribute can be found in the <a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#resolution_switching_different_sizes">Resolution Switching</a> section in that article.</p><h3>Conclusion</h3><p>So, to conclude, here are my tips on how to get confident on providing images on the Web:</p><ul><li>Understand the different image formats and what kind of images they perform best at (lossless and lossy codecs, and image types like photographs vs. illustrations with or without gradients).</li><li>Compress your images.</li><li>If you want to me <em>really</em> want to step up your game: Use the &lt;picture&gt; tag to provide images compressed in the AVIF image format in the browsers that support AVIF (because AVIF usually provides the smallest image sizes at an “acceptable” quality), and an other image format in the browsers that don’t support AVIF.</li><li>Measure your site’s performance and make sure your images are not contributing unreasonably to the total download time of your page by their big size.</li><li>Learn the correct syntax of the <em>sizes</em> attribute on the img-tag to ensure the right size of an image is downloaded runtime at the client.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14cd2e083e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The difference between width: auto; and width: 100%;]]></title>
            <link>https://forsethingvild.medium.com/the-difference-between-width-auto-and-width-100-a58e2ac7832f?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58e2ac7832f</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[kevin-powell]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 08:44:22 GMT</pubDate>
            <atom:updated>2024-12-02T06:56:16.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Again, this is a BIG thanks to <a href="https://www.youtube.com/kepowob/featured">Kevin Powell</a>, who has taught me so much about what I know about web design. He also taught me this, the difference between using width: auto; and width: 100%; (the video is <a href="https://www.youtube.com/watch?v=-st14lUQD3U">here</a>), but I kept forgetting it, so I thought I would make a post about it, possibly helping others with the same goldfish brain as mine 🙃</p><h3>width: auto; means use the available space</h3><p>With <em>use the available space, </em>it means that margins and paddings will be respected, and the element will not overflow its parent.</p><p>Kevin considers this a really unappreciated property in css, it basically helps us not screw things up, making it look good <em>automatically</em> 😉</p><p>This is the default value of the <em>width</em> property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*oEc3B3QGM3e2RZZANhHv-Q.gif" /></figure><h3>width: 100%; means be as big as the parent element</h3><p>With width: 100%;, you want the element to be as big as its parent. The consequence is that if you have set margins and paddings on the parent element, the element will overflow, which is something you don’t necessarily want.</p><p>So there you have it, the differences between width: auto; and width: 100%; To conclude, it is basically the consequence of the width: 100%; declaration that one should be aware of.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58e2ac7832f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes to CSS for Software Engineers for CSS Developers — Harry Roberts 2016 Talk]]></title>
            <link>https://forsethingvild.medium.com/notes-to-css-for-software-engineers-for-css-developers-harry-roberts-2016-talk-45c6b56c2acf?source=rss-c8803f8258c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/45c6b56c2acf</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[harry-roberts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-dev-simplified]]></category>
            <dc:creator><![CDATA[Ingvild Forseth]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 12:13:22 GMT</pubDate>
            <atom:updated>2021-02-08T12:23:13.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>Notes to CSS for Software Engineers for CSS Developers — Harry Roberts 2016 Talk</h3><p>You can see the talk here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwFn5nel3j6w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwFn5nel3j6w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwFn5nel3j6w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75f3ff0a9fde01f583dc324449bfb7d/href">https://medium.com/media/c75f3ff0a9fde01f583dc324449bfb7d/href</a></iframe><p>I think Roberts made a great talk, teaching me a lot of interesting principles from the history of computing, and how we can apply them to CSS.</p><p>CSS is a relatively “young” computer language, born in 1996. The idea behind this talk, is that we can benefit from applying the learnings of the 37-year old head-start since the release of the first modern programming language in 1959 (<a href="https://en.wikipedia.org/wiki/FLOW-MATIC">FLOW-MATIC</a>, according to Roberts).</p><p>I made this note for myself, hoping it would also benefit other that would like a quick reference when in need for a recap.</p><h3>DRY — Don’t Repeat Yourself (05:35)</h3><blockquote>“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”. — Don’t repeat yourself on <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Wikipedia</a></blockquote><p>Applied to CSS:</p><ul><li>Use variables (and mixins if you have use a pre-processor).</li></ul><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*cnJonGzLA5eiugn0o2-g7Q.png" /><figcaption>Using variables (CSS custom properties) will allow you to not duplicate code.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*8J13i4mLlTGqtbE93DNgAg.png" /><figcaption>Mixins can be used to group definitions together, so repetition is avoided.</figcaption></figure><h3>Single Source Of Truth (09:15)</h3><blockquote>Single source of truth is the practice of structuring information models and associated <a href="https://en.wikipedia.org/wiki/Database_schema">data schema</a> such that every data element is mastered (or edited) in only one place — Single source of truth on <a href="https://en.wikipedia.org/wiki/Single_source_of_truth#:~:text=In%20information%20systems%20design%20and,edited)%20in%20only%20one%20place.&amp;text=SSOT%20systems%20provide%20data%20that%20are%20authentic%2C%20relevant%2C%20and%20referable.">Wikipedia</a>,</blockquote><p>The philosophical principle behind DRY. Key data should exist only once in source. Increases confidence.</p><p>See the DRY principle above to see how to apply it to CSS.</p><h3>The Single Responsibility Principle (10:30</h3><blockquote>AKA: Do one thing, one thing only, and one thing well. — Harry Roberts</blockquote><p>Breaks it into individual concerns. Provides higher composability. The composable elements should have <em>one </em>reason to change.</p><p>Applied to CSS:</p><ul><li>Give the ingredients to the designer instead.</li><li>Don’t mix base (display), structural (padding) and cosmetic (color) responsibilities.</li></ul><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*bWHklgMStPkz1MVnCWXRuA.png" /><figcaption>This way of writing the CSS, makes it easier to swap or remove things out. The alternative would be to write a .sandwhich { … } class, with all the ingredients included. This you would have to reproduce almost in its entirety for every variation of the sandwich, leaving you with much more code.</figcaption></figure><p>Don’t do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*Pb5tawD82zUUyCDuEQDwXA.png" /></figure><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Eg_ZivJTonDi1hevJIcz4g.png" /><figcaption>This way of structuring the classes for buttons, does not mix the responsibilities for base, structure og cosmetic definitions. The classes can be combined to design the button you want. This is instead of having a .button-login {display: inline-block; padding: 2em; background-color: green; color: green} class, which is not really a re-usable class (how many login buttons are you planning to have on your page?)</figcaption></figure><h3>The Separation of Concerns (15:25)</h3><blockquote>“It is, that one is willing to study in depth an aspect of one’s subject matter in isolation for the sake of its own consistency, all the time knowing that one is occupying oneself only with one of the aspects. … ” — Separation of concerns on <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">Wikipedia</a></blockquote><p>It is not about performance or good quality code, but its main target it to write <em>understandable code</em>. They off course often go hand-in-hand, but the latter is the first and foremost goal — to be able to reason about things in isolation.</p><p>Applied to CSS:</p><ul><li>Only one hook per language/concern: The HTML should be able to change without breaking the CSS, the CSS should be able to change without changing the JS etc. Therefore</li><li>Only bind the CSS to CSS-based classes only.</li><li>Don’t use HTML tag-selectors like h2 etc.</li><li>Don’t use data-* attributes, they are reserved for the data layer.</li><li>Don’t use CSS classes to select items in your JS.</li></ul><p>Thus, do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*tka6Hcv6NL3YSD7eWmsVgQ.png" /><figcaption>The &lt;nav&gt;-tag for semantic concerns, the role=”navigation” for accessibility concerns, the “site-nav” class for stylistic concerns and the “js-site-nav” class for behavioural concerns.</figcaption></figure><p>A quick note to this: In my opinion, I think the dedicated JavaScript-classes prefixed with ‘js-’ looks a bit weird? A better alternative might be to use ids as JavaScript selectors instead, but then again, the JavaScript-functionality is perhaps something we want to attach to a “class” of elements, and not something that belongs to a specific element (identified with an id). I have watched <a href="https://www.youtube.com/channel/UCFbNIlppjAuEX4znoulh0Cw">Web Dev Simplified</a> (one of the YouTube gurus I love to learn from) use classes as the selectors as can be seen <a href="https://youtu.be/MDENx86nK4k">here</a>, so if you have som thoughts about this, <em>let me know</em>.</p><h3>Immutability (21:15)</h3><blockquote>An <strong>immutable object</strong> is an object whose state cannot be modified after it is created — Immutable object on <a href="https://en.wikipedia.org/wiki/Immutable_object">Wikipedia</a></blockquote><p>Provides confidence. Makes things predictable. Reduces cognitive overhead. If not complied to, unexpected side effects may be experienced.</p><p>Applied to CSS:</p><ul><li>Don’t overwrite/change classes in media-queries, use a different class instead.</li><li>Use !important statements only in utility helper-classes.</li><li>Avoid nesting.</li></ul><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*XzfWcGkurbOcdmSjI11E1Q.png" /><figcaption>A class will have two outcomes if you overwrite it in a media query, and it will require extra cognitive effort to remember that for different states of the application, the class will have different outcomes. Instead of overwriting the .col-6 class in the media query, introduce a new class and you will know exactly how it will behave.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*QrCsxZDPjTL50KXt6_ynCg.png" /><figcaption>Only use !important in utility helper-classes. This is to avoid specificity issues in which e.g. a .sub-content h2 { .. } class (in this example) would overrule the helper-class. (But nonetheless, we would never use a tag-selector in a CSS, thanks to the separation of concerns-principle above, right?)</figcaption></figure><p>Don’t do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*aVlvAtM1FF_nB5EGhVIWqQ.png" /><figcaption>Avoid nesting that overwrites styles like this, you are introducing a mutation (changing the .btn class, making it hard to reason about it and know what it does).</figcaption></figure><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*Ny73M1z18jG_H7mAEz6aaA.png" /><figcaption>Rather give each class a single responsibility, in line with the single responsibility-principle above). Then you will have the tools you need so you don’t have to overwrite styles by nesting.</figcaption></figure><h3>The Open/Closed Principle (27:20)</h3><blockquote>Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification […]; that is, such an entity can allow its behaviour to be extended without modifying its source code — Open-closed principle on <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle#:~:text=In%20object%2Doriented%20programming%2C%20the,without%20modifying%20its%20source%20code.">Wikipedia</a></blockquote><p>This applies to legacy CSS.</p><p>Applied to CSS:</p><ul><li>Never change anything at its source</li><li>A new or changed features should be implemented by adding new classes.</li><li>The new class can reuse code from the existing one by inheritance.</li><li>An existing class should only be changed to correct errors (it was a bug).</li></ul><p>Don’t do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*QS69VobJQiIJosIftfXugg.png" /><figcaption>Instead of overwriting existing behaviour (and also breaking the immutability principle in the same go), one should rather add a new class to implement or change a feature to avoid breaking any legacy CSS.</figcaption></figure><p>Do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*jAuCDlFd36GxDduJRyj-9Q.png" /><figcaption>Adding a new class that would also be needed to be added to the HTML makes us stay in control of our code and and avoid any unexpected changes.</figcaption></figure><h3>That’s all folks!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45c6b56c2acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>