<?xml version="1.0" encoding="utf-8"?>
  <rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    xmlns:georss="http://www.georss.org/georss"
    xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
  >
    <channel>
      <title>Piccalilli - Articles</title>
      <link>https://piccalil.li/</link>
      <atom:link href="https://piccalil.li/articles.xml" rel="self" type="application/rss+xml" />
      <description>We are Piccalilli. A publication dedicated to providing high quality educational content to level up your front-end skills.</description>
      <language>en-GB</language>
      <copyright>Piccalilli - Articles 2026</copyright>
      <docs>https://www.rssboard.org/rss-specification</docs>
      <pubDate>Mon, 16 Nov 2026 00:01:59 GMT</pubDate>
      <lastBuildDate>Mon, 16 Nov 2026 00:01:59 GMT</lastBuildDate>

      
      <item>
        <title>If we stop, we lose</title>
        <link>https://piccalil.li/blog/if-we-stop-we-lose/?ref=articles-rss-feed</link>
        <dc:creator><![CDATA[Andy Bell]]></dc:creator>
        <pubDate>Thu, 29 Oct 2026 11:55:00 GMT</pubDate>
        <guid isPermaLink="true">https://piccalil.li/blog/if-we-stop-we-lose/?ref=articles-rss-feed</guid>
        <description><![CDATA[<p>It's been a rather <em>morale draining</em> era in the making websites industry since the wider tech industry decided to gamble everything on LLMs. We at Piccalilli see it amongst the community and <em>feel it</em> ourselves.</p>
<p>You'll also have noticed the velocity of posts has slowed down somewhat on this website with no new courses announced either. There's a couple of reasons for that. First, <a href="https://bell.bz/in-response-to-the-death-of-web-development-education/">the numbers have taken a dramatic tumble</a> — <a href="https://molily.de/web-dev-education/">industry-wide</a> — but also, aside from being very busy in <a href="https://set.studio/">the studio</a>, we've been <em>tired</em>. Swimming against this particular current will do that, even for folks like us that have <em>always</em> operated like that.</p>
<p>Something else you might have noticed is that a lot of other educators have gone a lot <em>quieter</em> this year too. I'm writing this post today to hopefully try and fix that.</p>
<h2>A shot in the arm</h2>
<p>I had a delightful conversation with <a href="https://css-tricks.com/">CSS-Tricks</a> head honcho, <a href="https://geoffgraham.me/">Geoff</a>, yesterday. Aside from the excellent vibes as a result of CSS-Tricks <a href="https://css-tricks.com/css-tricks-has-a-new-owner/">being back as an independent publisher</a>, I started in a rather glum mood. After spending a few minutes listening to Geoff's exciting plans though I really perked up.</p>
<p>We're nowhere near CSS-Tricks here, but we've always looked up to them as an example of what years and years at the top of your game looks like. Sure, the DigitalOcean acquisition didn't work out, but the fact that the publication is not only back, but well up for the fight against the supposed death of web education is really inspiring to me. I <em>needed</em> that win, as did <a href="https://wil.to/posts/taking-back-css-tricks/">many others</a>.</p>
<p>I needed it so much, it's spurred me on to write this article to hopefully give us <em>all</em> a shot in the arm.</p>
<h2>There is no inevitable future and education will always matter</h2>
<p>A comment I see all the time is "we don't need articles and courses because we can just ask an LLM now", which I guess is true, but I could also eat an entire can of spray cheese. It ain't gonna nourish me!</p>
<p>AI technologies have given anyone the ability to bring their ideas to life, but to produce a high quality end product that <em>actually works</em> for the people it needs to work for requires experience, specialist skills and creativity. That <em>is</em> a reality, which aside from Silicon Valley's best efforts, is why there are still working developers out there, regardless of "frontier model" power. Human developer's experience is <em>necessary</em> because LLM outputs still (somehow, after hundreds of billions of investment) fall short.</p>
<p>Let me repeat that: their experience is <em>necessary</em>. Who inevitably contributed to that experience? Yep: educators.</p>
<p></p>
<h2>Let's get to work then</h2>
<p>This article is mainly addressed to fellow educators, but also to people that write on their personal blogs. <strong>You must keep going because people still need us</strong>. If we don't, we lose.</p>
<p>The LLM era is opening up an enormous skills gap that's only going to get wider as the industry continues to pull up the ladder, eliminating entry level positions. We're needed to help people really understand how all of this stuff <em>works</em>, so even if they are at <a href="https://piccalil.li/blog/are-peoples-bosses-really-making-them-use-ai/">the behest of LLM mandates</a>, they can produce better outputs.</p>
<p>The technology is going nowhere — that toothpaste is long out of the tube — but how many other hype cycles have underwhelmed in the end?</p>
<p>Spoiler, all of them</p>
<p>The economics of the AI industry simply do not work and the technology — albeit ever-present in development — will fall into its actual place eventually, as a <a href="https://bell.bz/the-logical-destination-of-llms/">niche tool</a>.</p>
<p>With all of this in mind, we're fighting back too, so <a href="https://piccalil.li/guest-authoring/">I'm opening up the guest authoring on this site again</a>, <a href="https://css-tricks.com/guest-writing/">just like Geoff is over on CSS-Tricks</a>. I'm determined to get this website <em>cooking</em> again and I would love to share <em>your</em> words with the rest of the industry.</p>
<p>Let's buck up our ideas and get cracking, everyone. There's lots to teach and I know we've got plenty of fight left in us.</p>
<p>To quote our very own <a href="https://wil.to/js4e/newsletter/mat-update-22/">Mat Marquis</a>:</p>
<blockquote>
<p>You and me, we’re not done until we say we’re done</p>
</blockquote>
<p>Don't let the bastards grind you down.</p>
        
        ]]></description>
        
      </item>
    
      <item>
        <title>Native masonry layouts with CSS grid lanes</title>
        <link>https://piccalil.li/blog/native-masonry-layouts-with-css-grid-lanes/?ref=articles-rss-feed</link>
        <dc:creator><![CDATA[Saleh Mubashar]]></dc:creator>
        <pubDate>Thu, 22 Oct 2026 11:55:00 GMT</pubDate>
        <guid isPermaLink="true">https://piccalil.li/blog/native-masonry-layouts-with-css-grid-lanes/?ref=articles-rss-feed</guid>
        <description><![CDATA[<p>Native masonry layouts have been a long time coming to CSS and after years of debate over how they should work and fit into the language, we finally have <code>display: grid-lanes</code>.</p>
<p>If you want the full backstory on how we got here, Sunkanmi Fafowora has a great <a href="https://css-tricks.com/masonry-layout-is-now-grid-lanes/">overview of the grid-lanes announcement</a> over on CSS-Tricks. Here, I want to focus on the technical side of masonry, why it took so long to get right, and how <code>display: grid-lanes</code> works.</p>
<h1>How we got here</h1>
<p>Masonry has been a long-running CSS challenge. Back in 2017, Rachel Andrew opened a <a href="https://github.com/w3c/csswg-drafts/issues/945">CSSWG issue</a> about creating a native Pinterest-style layout. As Rachel noted back then, the closest native CSS got to this was multi-column layout (column-count), but that flows items top-to-bottom. Masonry needs to flow items <em>across</em> rows, tightly packing them into whatever column currently has the most available vertical space.</p>
<p><img src="https://piccalil.b-cdn.net/images/blog/pintrest-masonry.jpg" alt="A browser screenshot of a pintrest page, showing a masonry layout, split over 3 columns" title="Pinterest’s masonry layout" /></p>
<p>That same year, Tab Atkins-Bittner shared a clever Grid hack to approximate the layout. It relied on knowing each item’s height in advance, making it less practical for dynamic content.</p>
<pre><code>.hacky-masonry {
  display: grid;
  grid: auto-flow dense 1px / repeat(3, 1fr);
}

/* Manually set each item's row span */
.item {
  grid-row: span 50; /* Matches the item's 50px height */
}
</code></pre>
<p>As cool as this hack was, having to know the exact height of every item ahead of time wasn’t very practical, especially when you’re dealing with dynamic content, where heights can change. When I spoke with Tab Atkins-Bittner for my piece on the <a href="https://css-tricks.com/masonry-watching-a-css-feature-evolve/">evolution of CSS Masonry</a>, they put the broader challenge of designing CSS layouts this way:</p>
<blockquote>
<p><em>“Flexbox was the first of the modern layout algorithms; we made a lot of mistakes and missteps while writing it, because we were trying to figure out how a modern layout model should work.”</em></p>
</blockquote>
<p>That same process of figuring things out played a role in masonry's development and until CSS had a better answer, many of us ended up reaching for David DeSandro’s legendary <a href="https://masonry.desandro.com/">Masonry.js</a> library instead.</p>
<p>But the challenge wasn't just figuring out how to make masonry work in CSS. There was also the question of how it should fit into the language. Should it be part of Flexbox, an extension of Grid, or its own display value? For years, the CSS Working Group went back and forth without settling on a final syntax.</p>
<p>Mozilla first explored adding masonry to Grid, and WebKit later picked up that approach. It lets you keep display: grid and use a special value for the tracks to enable masonry.</p>
<pre><code>.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
  grid-template-rows: masonry;
}
</code></pre>
<p>This kept Grid's familiar column definitions while letting the browser pack items vertically instead of aligning them into rows. You can read more about WebKit's reasoning in <a href="https://webkit.org/blog/16026/css-masonry-syntax/"><em>Help us choose the final syntax for Masonry in CSS</em></a>.</p>
<p>Google's Chromium team had a different take. They argued that masonry's layout algorithm was different enough from Grid to deserve its own layout mode, proposed as <code>display: masonry</code> .</p>
<pre><code>.masonry {
  display: masonry;
  masonry-template-tracks: repeat(auto-fill, minmax(14rem, 1fr));
  gap: 1rem;
}
</code></pre>
<p>Their reasoning, along with an alternative syntax, is explained in <em><a href="https://developer.chrome.com/blog/masonry">An alternative proposal for CSS masonry</a>.</em></p>
<p>The debate continued through several rounds of proposals, including WebKit's broader item-flow idea for unifying aspects of Grid and Flexbox, but that approach was eventually dropped in favor of a simpler direction.</p>
<p>In January 2025, the CSS Working Group agreed to reuse CSS Grid's track-definition and placement properties for masonry. By December 2025, the group had settled on a name for the new layout mode, <strong><code>grid-lanes</code></strong>. WebKit announced the direction in <a href="https://webkit.org/blog/17660/introducing-css-grid-lanes/"><em>Introducing CSS Grid Lanes</em></a>.</p>
<p></p>
<h1>How grid lanes works</h1>
<p>The nice thing about <code>display: grid-lanes</code> is that you don't have to figure out where every item goes yourself. You define the tracks along one axis, just as you would with regular CSS Grid and the browser handles placement along the other.</p>
<p>For a typical masonry layout, that means defining your columns with <code>grid-template-columns</code> and letting the browser stack items into whichever lane makes the most sense.</p>
<p>You still get familiar Grid properties like <code>grid-template-columns</code>, <code>repeat()</code>, <code>minmax()</code>, <code>gap</code>, and explicit placement. Under the hood, though, Grid Lanes uses a different layout algorithm: it <strong>maintains tracks along the grid axis</strong> and packs items along the stacking axis. That makes it possible to build responsive masonry layouts without calculating item heights yourself.</p>
<h2>A Basic Masonry Layout</h2>
<pre><code>.masonry {
  display: grid-lanes;
  grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
  gap: 1rem;
}
</code></pre>
<p>This defines as many columns as fit, with each column at least <code>14rem</code> wide. The browser handles the rest, placing items into lanes as it lays them out. Unlike regular Grid, items don't need to share row heights, so each lane can grow independently.</p>
<p>Here’s how this layout would look:</p>
<p><img src="https://piccalil.b-cdn.net/images/blog/masonry-wireframes.png" alt="A wireframe diagram comparing masonry website layouts for tablet and desktop. The left side shows a tablet view with a 2-column grid for screen widths 768px to 1024px. The right side shows a desktop view with a 3-column grid for screen widths 1024px and above." title="A simple masonry layout example" /></p>
<h2>The fill algorithm</h2>
<p>Unlike regular CSS Grid, Grid Lanes doesn't try to line everything up in rows. Instead, the browser keeps track of how much space each lane takes up and uses that to decide where the next item should go.</p>
<p>The process is pretty simple:</p>
<ol>
<li>Check how much each lane is filled.</li>
<li>Place the next item in a suitable lane, usually the shortest one.</li>
<li>Update that lane's position and repeat.</li>
</ol>
<p>For example, with three columns, the first three cards go into separate lanes. If column 2 is now the shortest, the next card goes there.</p>
<pre><code>.masonry {
  display: grid-lanes;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}
</code></pre>
<h2>Controlling item placement</h2>
<p>Most of the time, you'll let the browser handle placement. But you can still use familiar Grid properties when you want more control. For example, <code>grid-column: span 2</code> lets an item span two columns instead of occupying just one.</p>
<pre><code>.featured-item {
  grid-column: span 2;
}
</code></pre>
<p>The browser actually places these explicitly positioned and spanning items <em>first</em>, before it runs the masonry algorithm for the rest of the auto-placed items. Spanning items affects how the remaining space is distributed, so placement can get more complicated than simply choosing the shortest lane, especially in larger layouts with lots of moving pieces.</p>
<p>Since items can appear in a different visual order from their source order, it's also worth checking that the layout still makes sense when read from the HTML. This matters for accessibility, too, as screen readers generally follow the document order rather than the visual layout. We’ll cover this in more detail later.</p>
<h2>A note on fit-tolerance</h2>
<p>The Grid Lanes spec is still evolving, but its direction is becoming clearer. The CSS Working Group dropped the broader <code>item-*</code> proposal for unifying flow controls across layout modes and settled on <code>display: grid-lanes</code> for masonry. Another change is the rename of flow-tolerance to <strong><code>fit-tolerance</code></strong>, a property that helps control how the browser chooses between lanes of similar heights.</p>
<p>Say you have two lanes; one is <code>400px</code> tall and the other is <code>398px</code>. The second lane is technically shorter, but only by <code>2px</code>. With a tolerance of <code>1em</code> , the browser can treat both lanes as close enough in height and choose the lane that better preserves the source order, rather than always picking the shortest one. This can help prevent items from jumping ahead of earlier items just to fill tiny gaps.</p>
<p>Here’s how different values affect the layout:</p>
<pre><code>.masonry {
  fit-tolerance: 0; /* favor the shortest lane */
}

.masonry {
  fit-tolerance: 1em; /* Treat lanes within 1em as close enough */
}

.masonry {
  fit-tolerance: infinite; /* Prioritize source order over compact packing */
}
</code></pre>
<p>A value of <code>0</code> favors tighter packing, while a larger tolerance gives the browser more flexibility to keep items closer to their source order. <code>infinite</code> prioritizes source order, even if that leaves more empty space in the layout. The default is <code>normal</code>, which resolves to 1em.</p>
<div><h2>FYI</h2>
<p><code>infinite</code> prioritizes source order, but it won’t guarantee it in every case. Similarly, 0 removes the tolerance for treating lanes of similar heights as equivalent.</p>
</div>
<p></p>
<h2>Switching directions</h2>
<p>Masonry doesn't have to flow vertically. With Grid Lanes, the tracks you define also determine the direction items are packed in. When you define <code>grid-template-columns</code>, items are packed vertically into columns. When you define <code>grid-template-rows</code>, items are packed horizontally into rows. The first is the familiar Pinterest-style layout, while the second creates a brick-like arrangement.</p>
<p>Check out this <em><a href="https://ics-creative.github.io/260611_grid-lanes/brick.html">Waterfall and Brick demo</a>,</em> by <em>ICS Creative,</em> to switch between the two layouts and see the difference. Both use <code>display: grid-lanes</code>, just with different track definitions.</p>
<p>The WebKit team has also published the <a href="https://gridlanes.webkit.org/"><em>Field Guide to Grid Lanes</em></a>. It includes an interactive playground, a reference for the different properties and values, and six demos covering layouts like photo galleries, recipe cards, timelines, and pinboards.</p>
<h2>Subgrids in masonry layouts</h2>
<p>One of the arguments for keeping masonry part of CSS Grid was that it would preserve features like <code>subgrid</code>.</p>
<p>If masonry had its own <code>display: masonry</code> layout mode, getting nested elements to align with their parent's grid tracks could have required changes across multiple CSS specifications. Keeping masonry within the Grid model means subgrid can work alongside it.</p>
<p>Say you're building a masonry layout of recipe cards, each with a title, an image, and a list of ingredients. <code>subgrid</code> lets the cards use their parent's grid tracks rather than defining their own, making it easier to align their internal elements.</p>
<pre><code>.masonry-container {
  display: grid-lanes;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.recipe-card {
  display: grid;
  /* The card's internal columns align with the parent masonry grid */
  grid-template-columns: subgrid;
}
</code></pre>
<h1>Where we’re at today</h1>
<p>Grid Lanes has come a long way from the early proposals and workarounds, but there's still work to do. The specification is an Editor’s Draft, which means details can change as the <em>CSS Working Group</em> continues to refine the layout model.</p>
<p>Browser support is another thing to keep an eye on. As of writing this article, Grid Lanes works in Safari 26.4 and later, but support in other browsers is still evolving. Check <a href="https://caniuse.com/css-grid-lanes"><em>Can I Use</em></a> for the latest updates, and consider using a simpler fallback for browsers that don't support it.</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_C0DFFD9E054868E848ED727F19306D49CB155C963160AD9B419BF7E4D1EBF6AC_1792047319842_image.png" alt="A Can I Use screenshot showing only support for later versions of Safari" /></p>
<h1>Wrapping up</h1>
<p>Grid Lanes has come a long way from the early proposals and workarounds. Here's a quick recap of where things stand now:</p>
<ul>
<li>Masonry uses <code>display: grid-lanes</code> as a separate layout mode.</li>
<li>Lanes are defined by <code>grid-template-columns</code> or <code>grid-template-rows</code>.</li>
<li>Items are automatically placed into lanes based on available space.</li>
<li><code>fit-tolerance</code> controls how much difference between lanes is treated as a tie.</li>
<li>The DOM source order stays intact, even when the visual order differs.</li>
<li>Unsupported browsers can use a simpler fallback layout.</li>
</ul>
        
        ]]></description>
        
      </item>
    
      <item>
        <title>Stop buttons triggering zoom when they’re double tapped</title>
        <link>https://piccalil.li/blog/stop-buttons-triggering-zoom-when-theyre-double-tapped/?ref=articles-rss-feed</link>
        <dc:creator><![CDATA[Andy Bell]]></dc:creator>
        <pubDate>Wed, 23 Sep 2026 11:55:00 GMT</pubDate>
        <guid isPermaLink="true">https://piccalil.li/blog/stop-buttons-triggering-zoom-when-theyre-double-tapped/?ref=articles-rss-feed</guid>
        <description><![CDATA[<p>I stumbled across <a href="https://bsky.app/profile/renderg.host/post/3mvipol2rzk2m">this great project</a> by <a href="https://renderg.host/">Barry Prendergast</a>. It's a web-based radio player with a <em>lush</em> UI. On mobile I spotted that as I was rapidly flicking through the stations to find one that was on air, the browser was zooming in and out.</p>
<p>Here's a screen clip:</p>
<p></p><p>Watch the <a href="https://iframe.mediadelivery.net/embed/468647/040189f2-c87a-4fda-a3bf-c65bf2254edb?autoplay=false&amp;loop=false&amp;muted=false&amp;preload=true&amp;responsive=true">video</a>.</p><p></p>
<p>I thought this behaviour was related to their viewport meta tag setup, but they have that set up perfectly:</p>
<pre><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
</code></pre>
<p>Now, you could prevent the zooming by adding <code>, maximum-scale=1.0, user-scalable=no</code> to the <code>content</code> attribute, but <strong>don't do that</strong> because it prevents zooming at all, which is a <a href="https://www.w3.org/WAI/WCAG21/Understanding/resize-text.html">WCAG violation</a>.</p>
<p>What's actually happening here is the browser is responding to the double tap gesture, which in the case of Safari on iOS, zooms into the button element I'm tapping. Luckily there's a CSS one-liner for us that gets the job done.</p>
<pre><code>.button {
  touch-action: manipulation;
}
</code></pre>
<p>As per <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/touch-action">MDN</a>:</p>
<blockquote>
<p>Enable panning and pinch zoom gestures, but disable additional non-standard gestures such as double-tap to zoom. Disabling double-tap to zoom removes the need for browsers to delay the generation of <strong>click</strong> events when the user taps the screen. This is an alias for "<strong>pan-x pan-y pinch-zoom</strong>" (which, for compatibility, is itself still valid).</p>
</blockquote>
<p></p>
<p>Let's see it in action. First, here's a couple of buttons without <code>touch-action</code>. Try rapidly tapping on your phone/touch device:</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/emvBdae/c0ed51c7ebc182fe12fec6967a92c584">Buttons without touch-action applied</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<p><a href="https://cdpn.io/pen/debug/emvBdae/c0ed51c7ebc182fe12fec6967a92c584">This link</a> has no CodePen framing to make that easier for you</p>
<p>Here are the same buttons <em>with</em> <code>touch-action</code> applied:</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/myWOrzY/1c43253e5ffc8a38d68dd7fc42cccf7a">Buttons with touch-action applied</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<p>Again, <a href="https://cdpn.io/pen/debug/myWOrzY/1c43253e5ffc8a38d68dd7fc42cccf7a">here's a frameless version</a> for you</p>
<p>Handy!</p>
        
        ]]></description>
        
      </item>
    
      <item>
        <title>A decent custom checkbox pattern for until ::checkmark is ready</title>
        <link>https://piccalil.li/blog/a-decent-custom-checkbox-for-until-checkmark-is-ready/?ref=articles-rss-feed</link>
        <dc:creator><![CDATA[Andy Bell]]></dc:creator>
        <pubDate>Thu, 17 Sep 2026 11:55:00 GMT</pubDate>
        <guid isPermaLink="true">https://piccalil.li/blog/a-decent-custom-checkbox-for-until-checkmark-is-ready/?ref=articles-rss-feed</guid>
        <description><![CDATA[<p>Now that we can better customise <code>&lt;select&gt;</code> elements, it's only natural to side-eye other form <code>&lt;input&gt;</code> types that have caused us visual headaches.</p>
<p>Sure, we should be applying the <em>lightest</em> of touches to form elements, especially, but even with a bit of visual-massaging, checkboxes are limited, aside from a bit of <code>accent-color</code>.</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/pvebLwo/01786b2d24fcc35066571a56df54c09f">Standard checkbox with accent colour</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<p>There is a brighter future incoming, if you're to read the <a href="https://www.w3.org/TR/css-forms-1/#checkmark">spec</a>:</p>
<blockquote>
<p>The ::checkmark pseudo-element represents an indicator of whether the item is checked, and is present on checkboxes, radios, and option elements.</p>
<p>— <a href="https://www.w3.org/TR/css-forms-1/#checkmark">W3C forms level 1</a></p>
</blockquote>
<p>Match that with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/appearance#formal_syntax"><code>appearance: base</code></a>, which is also incoming, and we're looking at this sort of CSS:</p>
<pre><code>input[type="checkbox"] {
  appearance: base;
}

input[type="checkbox"]::checkmark {
  content: url("data:image/svg+xml,%3Csvg aria-hidden='true' focusable='false' width='24' height='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E %3Cpath fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m5 12l5 5L20 7' /%3E %3C/svg%3E");
}
</code></pre>
<p>We're miles off from that capability yet — it doesn't look like any browser is working on it —  so allow me to show you how to build a nice custom checkbox pattern for until we have the browser capabilities we're after.</p>
<p></p>
<h2>HTML first, always</h2>
<p>It's always right to start with some good quality markup:</p>
<pre><code>&lt;label for="custom-checkbox" class="checkbox"&gt;
  &lt;span class="checkbox__box"&gt;
    &lt;input type="checkbox" name="custom-checkbox" id="custom-checkbox" value="Some value that this control toggles"&gt;
    &lt;svg aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"&gt;
      &lt;path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m5 12l5 5L20 7" /&gt;
    &lt;/svg&gt;
  &lt;/span&gt;
  &lt;span&gt;A long label for this checkbox to make sure we get a nice wrapping behaviour&lt;/span&gt;
&lt;/label&gt;
</code></pre>
<p>The markup is pretty straightforward here. Inside the parent <code>&lt;label&gt;</code> — which is linked to the input both by being a parent <em>and</em> the <code>for</code>/<code>id</code> attributes — we have a container for the input and icon, along with a text label.</p>
<p>The reason I'm using <code>&lt;span&gt;</code> elements here is because aside from the input/SVG only <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Content_categories#phrasing_content">phrasing content</a> is permitted. I don't think a <code>&lt;div&gt;</code> would do any harm here, but it's best to do things right.</p>
<p>On the SVG checkmark element, there's an <code>aria-hidden="true"</code> attribute. This stops the SVG — a visual element — getting in the way for assistive technology. I've also added <code>focusable="false"</code>. This is actually a relic from the Internet Explorer days hell, but I keep it on visual only icons, just in case.</p>
<p>Right, we're in good shape. Let's make it look good.</p>
<p></p>
<h2>Some CSS</h2>
<p>The first thing to do is layout:</p>
<pre><code>.checkbox {
  display: flex;
  align-items: baseline;
  gap: 1em;
  text-wrap: balance;
}
</code></pre>
<p>Flex is more than capable here. I like to align on the baseline in this sort of context because as the viewport gets small and the text wraps, we don't want a vertically centered layout. It looks rubbish!</p>
<p>Speaking of balance, I'm using <code>text-wrap: balance</code> here for the same compressed viewport context and dealing with wrapping text. Keeping a consistent edge (rag) is extra important for small microcopy, such as labels.</p>
<p>Let's tackle the input itself.</p>
<pre><code>.checkbox input {
  margin: 0;
  width: 100%;
  height: 100%;
  appearance: none;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 0.2em; /* This is so the focus ring has a matching radius to the visual box */
}
</code></pre>
<p>We've got to be <em>really</em> careful here because we don't want to mess up the focusability of our element. Combining <code>appearance: none</code> and absolute positioning, our element is still there, but its no longer in the way, <em>visually</em>. It can still receive focus and will present a focus ring, which is exactly what we need!</p>
<p>Let's tackle the "box" part, which is also this <code>&lt;input&gt;</code>'s parent.</p>
<pre><code>.checkbox__box {
  position: relative;
  background: transparent;
  color: currentcolor;
  border: 1px solid;
  width: 1.4em;
  height: 1.4em;
  transform: translateY(0.75ex);
  flex-shrink: 0;
  border-radius: 0.2em;
}
</code></pre>
<p>A lot of this is self explanatory but I'll pick up the key parts:</p>
<ol>
<li>I'm using <code>position: relative</code> so the <code>&lt;input&gt;</code> stays inside this box</li>
<li>The <code>transform</code> rule is a <em>bit</em> of a magic-number but because it's a relative <a href="https://every-layout.dev/rudiments/units/"><code>ex</code>
unit</a>, it scales quite nicely, regardless of parent font size. Most importantly the <code>ex</code> enhances that <code>baseline</code> alignment <em>and</em> fixes the initial alignment of the <code>&lt;input&gt;</code></li>
</ol>
<p>I really like how <a href="https://ishadeed.com/article/aligning-list-icons/">Ahmad Shadeed approaches this</a> too. That's the beauty of CSS: there's plenty of ways to do things well! </p>
<p>Let's deal with the SVG checkmark next:</p>
<pre><code>.checkbox__box svg {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
  display: none;
  width: 1em;
  height: 1em;
}
</code></pre>
<p>I guess I could use <a href="https://piccalil.li/blog/getting-started-with-css-custom-properties/">logical properties</a> here, but we're positioning an icon in a box, so the "old" way works perfectly well.</p>
<p>The idea here is to visually hide the checkmark when the checkbox isn't checked and show it when it is. We'll deal with that CSS next.</p>
<div><h2>FYI</h2>
This is a situation that very few people will likely find themselves in. What I'd recommend is having a couple of SVG elements that get toggled in that context. 
</div>
<pre><code>.checkbox__box:has(input:checked) {
  background: white;
}

.checkbox__box input:checked + svg {
  display: block;
}
</code></pre>
<p>We're in checked state territory here. I'm setting a white background using <code>:has()</code> which is <em>yet another</em> <a href="https://piccalil.li/blog/some-little-ways-im-using-css-has-in-the-real-world/">useful use-case</a> for this endlessly handy addition to CSS.</p>
<p>The following block of CSS uses a traditional next sibling selector to show the SVG element when the input is checked. You could use <code>:has()</code> here too, if you're feeling fancy.</p>
<p>With all of that CSS in place, we're looking good.</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/MYpeyGd/f1c611739fe7d2308ca6102877c53711">Custom checkbox</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<p></p>
<h2>This approach could also work for radio buttons</h2>
<p>There's nothing stopping you using this approach for radio buttons. Check out this demo where I'm using a circle icon instead of a checkmark. It works well!</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/XJMKKep/edef02c55d0d972b66682ee3443858bb">Custom radio buttons</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<h2>The em units usage allows this whole component to scale</h2>
<p>The eagle eyed amongst us will have noticed that aside from the <code>transform</code> rules, I've consistently use <code>em</code> units. The reason for this is so our checkbox can scale with no other intervention.</p>
<p></p><p>See the Pen <a href="https://codepen.io/piccalilli/pen/QwpEmZw/df33cad21fa4c40a91912bb559886c1b">Custom checkbox - massive edition</a> by Andy Bell (<a href="https://codepen.io/piccalilli/">@piccalilli</a>) on <a href="https://codepen.io">CodePen</a>.</p><p></p>
<p>The only change here, versus the first demo is a <code>font-size</code> declaration on the <code>.checkbox</code> component.</p>
<p>A handy pattern, right?</p>
<hr />
<p>A big thanks to <a href="https://jakearchibald.com/">Jake Archibald</a> and <a href="https://heydonworks.com/">Heydon Pickering</a> for checking my homework.</p>
        
        ]]></description>
        
      </item>
    
      <item>
        <title>A look at the geolocation HTML element and how it works</title>
        <link>https://piccalil.li/blog/a-look-at-the-geolocation-html-element-and-how-it-works/?ref=articles-rss-feed</link>
        <dc:creator><![CDATA[Daniel Schwarz]]></dc:creator>
        <pubDate>Thu, 20 Aug 2026 11:55:00 GMT</pubDate>
        <guid isPermaLink="true">https://piccalil.li/blog/a-look-at-the-geolocation-html-element-and-how-it-works/?ref=articles-rss-feed</guid>
        <description><![CDATA[<p>The <code>&lt;geolocation&gt;</code> HTML element does exactly what you might think it does. It’s a dedicated element that gets the user’s location, either once or continuously. The options are set using HTML attributes instead of JavaScript, but JavaScript is still needed. However, <code>&lt;geolocation&gt;</code> requires <em>fewer lines</em> of JavaScript and also offers superior error and permission handling. In fact, the <code>&lt;geolocation&gt;</code> element started off as an all-purpose <code>&lt;permission&gt;</code> element, but is now dedicated to handling geolocation.</p>
<p>Fewer lines of code is always a good thing, but it’s the permission prompt that’s key here. When using the aging Geolocation JavaScript API, denying permission at any point can lock the user out with no way to recover unless they change the browser or operating system permissions manually. This can be a painful experience, especially for users that aren’t tech-savvy. Plus, as developers, we have to get the Permissions API involved.</p>
<p>Whereas, the <code>&lt;geolocation&gt;</code> element offers:</p>
<ul>
<li>Better error handling, and where applicable, recovery handholding</li>
<li>User-controlled permission prompting, even if the user denied permission previously</li>
<li>Auto-location if the user granted permission previously</li>
<li>A styleable granted state via the <code>:granted</code> CSS pseudo-class</li>
</ul>
<p><code>&lt;geolocation&gt;</code> is better in every way except browser support (it requires Chrome 144+), so in this article, I’ll explain how to use it alongside the older current Geolocation JavaScript API so that users get the better experience, if the new element is available.</p>
<p></p>
<h2>Requesting the user’s location using <code>&lt;geolocation&gt;</code></h2>
<p>The <code>&lt;geolocation&gt;</code> element accepts several attributes that largely correspond to the options of the <code>getCurrentPosition()</code> and <code>watchPosition()</code> methods of the aging Geolocation API.</p>
<p>Firstly, the <code>accuracymode</code> attribute accepts two values — <code>approximate</code> (which is the default value) and <code>precise</code>.</p>
<p><code>accuracymode=approximate</code> is equivalent to the <code>enableHighAccuracy: false</code> option (again, the default) from the Geolocation API, whereas <code>accuracymode=precise</code> is equivalent to <code>enableHighAccuracy: true</code>, which provides a more accurate location if the device is able to get one.</p>
<p>The <code>autolocate</code> boolean attribute attempts to get the user’s location automatically, assuming that they’ve granted the website permission previously.</p>
<p>The <code>watch</code> boolean attribute is equivalent to calling the <code>watchPosition()</code> method instead of the <code>getCurrentPosition()</code> method. <code>getCurrentPosition()</code> fetches the user’s location once, whereas <code>watchPosition()</code> tracks their location over time. Like <code>accuracymode=precise</code> and <code>enableHighAccuracy: true</code>, this drains the battery faster.</p>
<p>The <code>onlocation</code> event handler attribute can be used to execute JavaScript whenever location data or error information is passed to the browser.</p>
<p>What the <code>&lt;geolocation&gt;</code> element doesn’t offer, though, is the ability to specify the <code>timeout</code> (how long the browser should wait for a response) or <code>maximumAge</code> (how old a cached location can be). Instead the browser handles these as it sees fit, which is actually a good thing, because choosing the right values on a case-by-case basis is a complexity that we just don’t need.</p>
<p>In practice, this is how you might use <code>&lt;geolocation&gt;</code>:</p>
<pre><code>&lt;!-- Precisely autolocate and follow the user --&gt;
&lt;geolocation accuracymode="precise" autolocate watch&gt;
  &lt;!-- Render this when &lt;geolocation&gt; is unsupported --&gt;
  &lt;button id="fallbackButton"&gt;Use precise location&lt;/button&gt;
&lt;/geolocation&gt;
</code></pre>
<p>That is, of course, not including the JavaScript side of <code>&lt;geolocation&gt;</code> nor the Geolocation (JavaScript) API fallback. If you just want the full code then you’re looking for the <code>getCurrentPosition()</code> version and <code>watchPosition()</code> version. Note that geolocation doesn’t work in insecure contexts, so while the logic is sound, the CodePen demos won’t actually work. They’re raw-logic templates anyway, not fully working demonstrations.</p>
<p>Anyway, let’s get into the JavaScript of it all, starting with the JavaScript that sits on the other side of that <code>&lt;geolocation&gt;</code> markup.</p>
<h2>Handling the <code>&lt;geolocation&gt;</code> data with JavaScript</h2>
<p>First, we want to make sure that <code>&lt;geolocation&gt;</code> is supported with <code>if ("HTMLGeolocationElement" in window)</code>. If it is, then we select it with <code>const geoElement = document.querySelector("geolocation")</code>.</p>
<p>Unfortunately, we then have to dive into the most complex part of <code>&lt;geolocation&gt;</code> — it’s validity — where the <code>isValid</code> property returns <code>true</code> or <code>false</code> and the <code>invalidReason</code> property returns <code>""</code> (an empty string) or an enumerated value stating the reason.</p>
<p>These reasons mostly come down to developer oversight, so users <em>shouldn’t</em> encounter these ‘blockers’, but if they do, the <code>&lt;geolocation&gt;</code> button will be disabled. Here are the scenarios in which that can happen (note that the blockers are ordered by severity, and that <code>invalidReason</code> only returns the most severe one):</p>
<ul>
<li><code>illegal_subframe</code>: the <code>&lt;geolocation&gt;</code> element is nested within a <code>&lt;fencedframe&gt;</code> or insecure <code>&lt;iframe&gt;</code> (the latter of which is why the CodePen demos don’t work)</li>
<li><code>unsuccessful_registration</code>: the page has more than three <code>&lt;geolocation&gt;</code> elements</li>
<li><code>recently_attached</code>: the <code>&lt;geolocation&gt;</code> element has only recently been attached to the DOM (this blocker expires fairly quickly)</li>
<li><code>intersection_changed</code>: the <code>&lt;geolocation&gt;</code> element is moving</li>
<li><code>intersection_out_of_viewport_or_clipped</code> : the <code>&lt;geolocation&gt;</code> element isn’t within the viewport fully</li>
<li><code>intersection_occluded_or_distorted</code>: something is obscuring the <code>&lt;geolocation&gt;</code> element</li>
<li><code>style_invalid</code>: the <code>&lt;geolocation&gt;</code> element is styled in a way that isn’t allowed (more on this later)</li>
</ul>
<p>As you can see, these blockers are permanently avoidable as long as we catch and fix them. Let’s have a proper look at how <code>invalidReason</code> reports these blockers, though.</p>
<p>As the JavaScript comment below describes, <code>isValid</code> always returns <code>false</code> at first, while <code>invalidReason</code> returns <code>recently_attached</code>. This basically disables the <code>&lt;geolocation&gt;</code> button for a fraction of a second to prevent clickjacking. That is, unless a blocker of higher severity applies. We don’t actually need the line below, it’s there just to show you how <code>&lt;geolocation&gt;</code> will never be valid when the page loads.</p>
<pre><code>/* At first, isValid === false and invalidReason === "recently_attached"
unless isValid === false and invalidReason === "a reason of higher severity" */
console.warn(`isValid: ${geoElement.isValid}, invalidReason: ${geoElement.invalidReason}`);
</code></pre>
<p>If <code>&lt;geolocation&gt;</code> then becomes invalid for a more permanent reason, <code>isValid</code> will obviously remain <code>false</code>, so we can’t use the <code>validationstatuschange</code> event listener here. However, we can wrap the line in <code>setTimeout()</code> (as below). This will either log a new blocker into the console, or log that <code>isValid</code> is <code>true</code> (in which case <code>invalidReason</code> will be an empty string).</p>
<pre><code>/* After ~300ms, when &lt;geolocation&gt; is no longer ‘recently attached’ (to the DOM)
either isValid === true and invalidReason === "" (an empty string)
or isValid === false and invalidReason === "the reason with the highest severity" */
setTimeout(() =&gt; {
  console.log(`isValid: ${geoElement.isValid}, invalidReason: ${geoElement.invalidReason}`);
}, 300);
</code></pre>
<p>If the validation status changes later, <em>then</em> we can use the <code>validationstatuschange</code> event listener (again, as below). Note that if there are no persistent blockers, this will fire almost immediately as <code>invalidReason</code> switches from <code>recently_attached</code> to an empty string.</p>
<pre><code>/* If the validity of &lt;geolocation&gt; changes */
geoElement.addEventListener("validationstatuschange", () =&gt; {
  if (geoElement.isValid) {
    /* &lt;geolocation&gt; is valid (if there aren’t any blockers,
    it will become valid after it’s no longer ‘recently attached’ */
  } else {
    console.error(`&lt;geolocation&gt; invalid: ${geoElement.invalidReason}`);
  }
});
</code></pre>
<p>Now that you know how to debug the validation status and permanently fix any persistent blockers, let’s talk about the <em>permission</em> status.</p>
<p>We’re given a few properties and events to work with:</p>
<ul>
<li><code>initialPermissionStatus</code>: a property that returns <code>denied</code>, <code>granted</code>, or <code>prompt</code> (i.e., neither) based on the permission status when the page first loaded</li>
<li><code>permissionStatus</code>: the <em>current</em> permission status</li>
<li><code>promptaction</code>: an event that fires when the user denies or grants permission from the <code>&lt;geolocation&gt;</code> permission prompt dialog</li>
<li><code>promptdismiss</code>: fires when the user dismisses the dialog, in which case the <code>permissionStatus</code> remains unchanged</li>
</ul>
<pre><code>/* Determine the initial permission status */
if (geoElement.initialPermissionStatus === "denied") {
  /* The user previously denied permission */
} else if (geoElement.initialPermissionStatus === "granted") {
  /* The user previously granted permission */
} else if (geoElement.initialPermissionStatus === "prompt") {
  /* The user hasn’t made a choice */
}

/* If the user denies or grants permission */
geoElement.addEventListener("promptaction", () =&gt; {
  if (geoElement.permissionStatus === "denied") {
    /* The user denied permission */
  } else if (geoElement.permissionStatus === "granted") {
    /* The user granted permission */
  }
});

/* If the user dismisses the prompt */
geoElement.addEventListener("promptdismiss", () =&gt; {
  if (geoElement.permissionStatus === "denied") {
    /* The permission state remained denied */
  } else if (geoElement.permissionStatus === "granted") {
    /* The permission state remained granted */
  } else if (geoElement.permissionStatus === "prompt") {
    /* The permission state remained prompt */
  }
});
</code></pre>
<p>That being said, I honestly don’t know what we’d need any of that for. If the user previously denied permission, for example, the <code>&lt;geolocation&gt;</code> permission prompt dialog would enable the user to recover from that automatically:</p>
<p><img src="https://piccalil.b-cdn.net/images/blog/geolocation-1.png" alt="Two confirmation boxes. One reads &quot;You previously didn't allow location for this site&quot; and the other reads &quot;To use your location on this site, give Chrome access&quot;" /></p>
<p>This is in contrast to the older Geolocation API, which is unlikely to help users recover. In this case we need to read the permission status, manage the state of the component accordingly, and provide recovery instructions so that users can grant access manually, but <code>&lt;geolocation&gt;</code> takes care of all of that.</p>
<p>What you <em>will</em> need is the new <code>location</code> event, which fires whenever the browser passes location data (<code>geoElement.position</code> in this case) or error information (<code>geoElement.error</code>) to us.</p>
<p>Then, in the event listener callback, assuming that <code>geoElement.position</code> is truthy, we can access <code>position.coords</code> and <code>position.timestamp</code>, synthesizing the location data like this:</p>
<pre><code>/* If the browser passes location data or error information */
geoElement.addEventListener("location", () =&gt; {
  /* If location data */
  if (geoElement.position) {
    /* Synthesize the data */
    const {
      latitude,
      longitude,
      altitude,
      accuracy,
      altitudeAccuracy,
      heading,
      speed
    } = geoElement.position.coords;

    const timestamp = geoElement.position.timestamp;
  } else if (geoElement.error) {
    /* If error information */
  }
});
</code></pre>
<p>However, if <code>geoElement.error</code> is truthy, we can access <code>error.message</code> (that’s for us to log into the console) and <code>error.code</code>, which is much more suitable for error handling.</p>
<p>In short, there are three possible error codes, each with an associated constant so that we don’t need to remember what each error code represents. So <code>1</code> represents <code>PERMISSION_DENIED</code>, <code>2</code> represents <code>POSITION_UNAVAILABLE</code>, and finally, <code>3</code> represents <code>TIMEOUT</code>, and then we just evaluate them like this:</p>
<pre><code>/* If the browser passes location data or error information */
geoElement.addEventListener("location", () =&gt; {
  if (geoElement.position) {
    /* If location data */
  } else if (geoElement.error) {
    /* If error information */
    console.error(`&lt;geolocation&gt; error: ${geoElement.error.message}`);

    if (geoElement.error.code === geoElement.error.PERMISSION_DENIED) {
      /* No HTTPS or server misconfiguration */
    } else if (geoElement.error.code === geoElement.error.POSITION_UNAVAILABLE) {
      /* No location source (GPS satellite or nearby Wi-Fi network/cellular tower) */
    } else if (geoElement.error.code === geoElement.error.TIMEOUT) {
      /* Location source detection or hardware took too long */
    }
  }
});
</code></pre>
<p><code>PERMISSION_DENIED</code> means that the website isn’t being served over HTTPS (the browser denied permission), or that there’s some kind of server misconfiguration (the server denied permission), but those two errors are permanently fixable and shouldn’t occur in production.</p>
<p>The only way to deny permission (as far as I’m aware) is to block location access from the browser settings, then click on the <code>&lt;geolocation&gt;</code> button, then choose to continue denying. In my opinion, that’s not likely to happen and doesn’t warrant an error message anyway. There isn’t a denial mechanism for OS-level blocks so as not to make the impression that the browser can enforce one. In short, I don’t think we need to do anything for <code>PERMISSION_DENIED</code>.</p>
<p>And to clarify, because <code>&lt;geolocation&gt;</code> is user-invoked, <code>&lt;geolocation&gt;</code> itself never sets the permission status to denied (again, as far as I know).</p>
<p><code>POSITION_UNAVAILABLE</code> means that the device can’t detect a location source (nearby Wi-Fi networks and cellular towers as well as GPS satellites) to determine the location. Using a VPN or visiting the website via an in-app browser could cause this error too, so this is the trickiest error to convey to users.</p>
<p><code>TIMEOUT</code> means that the location source detection or hardware took too long, and that users should try again.</p>
<p>How you communicate errors to users is totally up to you.</p>
<p></p>
<h2>Falling back to the Geolocation JavaScript API</h2>
<p>Ready for round two? Now we’re going to do the same thing but with the aging Geolocation API, which is supported in every browser, but kind of a headache.</p>
<p>This is where we’re at currently:</p>
<pre><code>/* If &lt;geolocation&gt; is supported */
if ("HTMLGeolocationElement" in window) {
  /* What we covered in the previous section */
} else {
  /* What we’re focusing on now (the fallback) */
}
</code></pre>
<p>Within that <code>else</code> block, which runs when <code>&lt;geolocation&gt;</code> isn’t supported, we start off by selecting the fallback button (<code>const fallbackButton = document.querySelector("#fallbackButton")</code>). If you recall, this is nested within <code>&lt;geolocation&gt;</code> so that it’s ignored when <code>&lt;geolocation&gt;</code> <em>is</em> supported.</p>
<p>After that we create a function (<code>updateState()</code>) that manages the component state and provides recovery instructions. As arguments we supply the <code>state</code> as a string (<code>‌granted</code>, <code>‌prompt</code>, or <code>‌denied</code>, corresponding with the <code>permissionStatus</code>), and optionally, <code>statusMessage</code>, which’ll be used to convey status messages to the user. I don’t want to make any assumptions about your component, so how you convey the <code>statusMessage</code> and expand upon <code>updateState()</code> is up to you.</p>
<p>If <code>state === "denied"</code>, we disable the button with <code>fallbackButton.disabled = true</code> and provide some kind of recovery instruction of which should be passed as the second argument of the function. The reason why we disable the button is that <em>this</em> Geolocation API isn’t user-invoked, so to protect the user from spam requests, the browser can suppress requests and send the API straight to jail without passing go, triggering <code>PERMISSION_DENIED</code>. Additionally, if we make the API user-invoked (as we have), users can spam the button themselves and basically shadowblock themselves, but disabling the button fixes that.</p>
<p>If <code>state === "granted"</code> or <code>state === "prompt"</code>, we can enable the button (<code>fallbackButton.disabled = false</code>).</p>
<p>Now is a good time to mention that the earlier JavaScript code for the <code>&lt;geolocation&gt;</code> element works regardless of whether the element has the <code>watch</code> attribute or not. However, when using this older Geolocation API, there are two additional things that we need to take care of when trying to keep track of the user’s location continuously. The first thing is the watcher ID, which is returned by the <code>watchPosition()</code> method. Knowing this ID enables us to clear the watcher before registering a new one, which is a must-do for performance reasons.</p>
<p>So we <code>let watcherID = null</code> for now, and then we create the function that attempts to get the location (<code>getLocation()</code>), and the first thing that we do within that function, assuming that <code>watcherID !== null</code> (meaning that it’s been set before), is clear the watcher using <code>navigator.geolocation.clearWatch(watcherID)</code> and make <code>watcherID = null</code> again:</p>
<pre><code>/* A function for getting the location */
const getLocation = () =&gt; {
  /* If a watcher has already been registered */
  if (watcherID !== null) {
    /* Unregister it */
    navigator.geolocation.clearWatch(watcherID);
    watcherID = null;
  }
}
</code></pre>
<p>Then we disable the button using <code>fallbackButton.disabled = true</code> to, again, prevent spam clicks. If you want to bake some kind of loading indicator in, feel free to, but <code>&lt;geolocation&gt;</code> doesn’t.</p>
<p>After that we call <code>navigator.geolocation.watchPosition()</code>, setting <code>watcherID</code> to the returned watcher ID. This method has three parameters — success, error, and options.</p>
<pre><code>watcherID = navigator.geolocation.watchPosition(
  (position) =&gt; {
    /* Success */
  },
  (error) =&gt; {
    /* Error */
  },
  {
    /* Options */
  }
);
</code></pre>
<p>For the success callback function we synthesize the location data similarly to last time, then call <code>updateState("granted")</code>.</p>
<p>For the error callback function (optional but highly recommended) we clear the watcher and, again, make <code>watcherID = null</code>, but otherwise run the same error handling logic that <code>&lt;geolocation&gt;</code> runs. However, there are more circumstances in which the errors can occur.</p>
<p>For example, because <code>watchPosition()</code> and <code>getCurrentPosition()</code> aren’t necessarily user-invoked, there are more scenarios in which users are able to deny access, triggering the <code>PERMISSION_DENIED</code> error. Accordingly, we should call <code>updateState("denied", "Permission denied (try this or that)")</code>, offering a useful status message and clear recovery instructions.</p>
<p>Similarly, <code>POSITION_UNAVAILABLE</code> can also be triggered by an OS-level block, since not all web browsers catch this during the permission prompt dialog. <code>updateState("prompt", "Position unavailable (try this or that)")</code> is what we’re looking for this time.</p>
<p>Finally, another scenario that doesn’t occur with <code>&lt;geolocation&gt;</code> but does with <em>this</em> Geolocation API, is that if the browser prompts the user to grant permission at the OS-level, but then the user cancels their request, that can trigger the <code>TIMEOUT</code> error. Either way, call <code>updateState("prompt", "Request timed out (try this or that)”)</code>, once again tweaking it to your liking.</p>
<p>As you can see, the error reporting isn’t the best. Sometimes the error isn’t identified correctly, and even when it is, the error can occur for various reasons, which makes it difficult for us to convey a useful status message and clear recovery instructions. <code>&lt;geolocation&gt;</code> handles this better — the errors are identified correctly, and the nature of <code>&lt;geolocation&gt;</code> ensures that certain errors never occur to begin with. But why the error categories? Why not tell us exactly what went wrong?</p>
<p>Well, the reason is to make fingerprinting more difficult, and while we can totally put in the extra work to pinpoint the exact problem, simply stating what happened and what the user should do next is perfectly fine. Of course, <code>error.message</code> tells us more than <code>error.code</code> does, but the messages can be a bit vague and differ in every web browser, so we can’t read them or even output them reliably.</p>
<p>Anyway, the optional third parameter expects an object where we can set:</p>
<ul>
<li><code>enableHighAccuracy</code>: <code>true</code> or <code>false</code></li>
<li><code>timeout</code>: <code>20000</code> (20 seconds) is reasonable if <code>enableHighAccuracy: true</code>, <code>3000</code> - <code>5000</code> otherwise</li>
<li><code>maximumAge</code>: <code>0</code> for turn-by-turn navigation, <code>5000</code> - <code>10000</code> (5-10 seconds) for live tracking, <code>300000</code> - <code>600000</code> (5-10 minutes) for frequent updates (e.g., weather)</li>
</ul>
<p>I’d rather that the web browser choose the <code>timeout</code> and <code>maximumAge</code> for us, especially considering the impact that they have on the <code>TIMEOUT</code> error and device battery, but of course, that’s exactly what <code>&lt;geolocation&gt;</code> does.</p>
<pre><code>/* Attempt to get the location and store the returned ID */
watcherID = navigator.geolocation.watchPosition(
  /* If location data is passed (like before) */
  (position) =&gt; {
    /* Synthesize the data (again, like before) */
    const {
      latitude,
      longitude,
      altitude,
      accuracy,
      altitudeAccuracy,
      heading,
      speed
    } = position.coords;

    const timestamp = position.timestamp;

    /* And update the state */
    updateState("granted");
  },

  /* If error information is passed (yep, like before) */
  (error) =&gt; {
    console.error(`Geolocation error: ${error.message}`);

    /* Again, unregister the watcher (if necessary) */
    if (watcherID !== null) {
      navigator.geolocation.clearWatch(watcherID);
      watcherID = null;
    }

    if (error.code === error.PERMISSION_DENIED) {
      /* No HTTPS, server misconfiguration, or the user denied access */
      updateState("denied", "Permission denied (try this or that)");
    } else if (error.code === error.POSITION_UNAVAILABLE) {
      /* No location source (GPS satellite or nearby Wi-Fi network/cellular tower) or OS-level access */
      updateState("prompt", "Position unavailable (try this or that)");
    } else if (error.code === error.TIMEOUT) {
      /* Location source detection or hardware took too long, or the user canceled their request */
      updateState("prompt", "Request timed out (try this or that)");
    }
  },
  {
    enableHighAccuracy: true,
    timeout: 20000 /* 20 seconds because enableHighAccuracy: true */,
    maximumAge: 0 /* 0 seconds because we’re demanding high accuracy */
  }
);
</code></pre>
<p>After that we need to query the permission status using the Permissions API (<code>navigator.permissions.query({ name: "geolocation" }).then((permissionStatus) =&gt; { /* ... */ })</code>), and then execute all of the aforementioned logic based on that.</p>
<p>If <code>permissionStatus.state === "granted"</code>, we call <code>getLocation()</code>, which is essentially what the <code>autolocate</code> attribute does. If you don’t want autolocation, simply delete this part. If it’s anything else, we basically determine the initial state by calling <code>updateState(permissionStatus.state)</code>.</p>
<pre><code>/* Query the permission status */
navigator.permissions.query({ name: "geolocation" }).then((permissionStatus) =&gt; {
  /* Equivalent to the autolocate attribute */
  if (permissionStatus.state === "granted") {
    getLocation();
  } else {
    /* React accordingly */
    updateState(permissionStatus.state);
  }
});
</code></pre>
<p>Finally, make the button respond to clicks:</p>
<pre><code>/* If the user clicks the fallback button */
fallbackButton.addEventListener("click", () =&gt; {
  getLocation();
});
</code></pre>
<p>If we only want to get the user’s location once (rather than watch it continuously), these are the modifications that we need to make:</p>
<ul>
<li>Remove everything related to the <code>watcherID</code></li>
<li>Swap <code>watchPosition()</code> for <code>getCurrentPosition()</code></li>
<li>Provide different settings for the options parameter</li>
</ul>
<p>Note that the <code>change</code> event, which could help us update the state whenever the user changes their browser-level permission status, doesn’t fire in Safari. Besides, the standard browser behavior is to ask users to refresh the page, so let’s stick with that.</p>
<p>One more thing — I wanted the button to say “Refresh precise location” and “Getting precise location…” at certain points, but <code>&lt;geolocation&gt;</code> doesn’t do this, so I didn’t either. That’s up to you, though.</p>
<p></p>
<h2>Styling the <code>&lt;geolocation&gt;</code> element</h2>
<p><code>&lt;geolocation&gt;</code> has a <code>:granted</code> pseudo-class. If we throw <code>:not(:granted)</code> into the mix, we can target the prompt/denied states too:</p>
<pre><code>geolocation {
  &amp;:granted {
    /* Permission granted */
  }

  &amp;:not(:granted) {
    /* Permission not granted */
  }
}
</code></pre>
<p>With the Geolocation API, we can toggle classes as needed to achieve the same effect, but honestly, I’ve never felt compeled to style such a button in this way. Personally, I’d like to be able to change the icon and text (maybe this is something that you can bake into the <code>updateState()</code> function), but this is one of the things that the <code>&lt;geolocation&gt;</code> element outright forbids.</p>
<p><img src="https://piccalil.b-cdn.net/images/blog/geolocation-2.png" alt="A button element labelled &quot;use precise location&quot;" /></p>
<p>Before we dive into all <em>that</em>, here’s a rundown of <code>&lt;geolocation&gt;</code> rules stated by Google’s explainer and Mozilla’s explainer:</p>
<ul>
<li>There must be sufficient color contrast</li>
<li>The alpha channel must resolve to <code>1</code> (so no transparency)</li>
<li>The minimum and maximum width, height, and font size must be respected</li>
<li>Negative margins and outline offsets aren’t allowed either</li>
<li>Distortion effects — including linear gradients — are banned</li>
</ul>
<p>It’s also worth noting that some of these rules function like guardrails (for example, you physically can’t style the height above 50px), whereas others cause <code>invalidReason</code> to return <code>style_invalid</code> and the <code>&lt;geolocation&gt;</code> button to be disabled.</p>
<p>Some of the rules seem to have changed (or are currently bugged). <code>&lt;geolocation&gt;</code> doesn’t respect <code>prefers-color-scheme</code> either, but it’s a developing feature, so I’m not going to comment on all of that too much. I’ll just state what I do and don’t like:</p>
<ul>
<li>I don’t like that the button becomes disabled because of a style (guardrails are better, but I don’t really like either)</li>
<li>I don’t like the forced icon and text, and I’m also not too happy about not being able to use gradients or <code>corner-shape</code></li>
<li>I can make peace with everything else because I’d normally design within those guardrails anyway</li>
<li>The text being localized into different languages is very cool, but it’s a first for web standards and I don’t currently enjoy that it’s a thing for only these permission buttons</li>
</ul>
<p>While I obviously support preventing web authors from tricking users into giving away their location, I think it’d be better if <code>&lt;geolocation&gt;</code> were fully styleable and the permission prompt dialog be ultra clear about what the user is about to commit to.</p>
<p>Even though I can style the background, color, border, border radius, and box shadow how I’d want them (as in the image below, which is most of what I’d want), this feels like a step back towards unstyleable controls. Having said that, this approach means well (<em>extremely</em> well), so I can’t wait to see where this goes (and frankly, to be able to throw the aging Geolocation API in the bin).</p>
<p><img src="https://piccalil.b-cdn.net/images/blog/geolocation-3.png" alt="A purple button element with white text, labelled &quot;use precise location&quot;" /></p>
<h2>What now? What else?</h2>
<p>When all web browsers support <code>&lt;geolocation&gt;</code>, the user experience and developer experience will improve dramatically.</p>
<p>But that’s not all!</p>
<p>What was once the <code>&lt;permission&gt;</code> element is now the <code>&lt;geolocation&gt;</code> element, <code>&lt;install&gt;</code> element (which facilitates the installation of Progressive Web Apps), <code>&lt;usermedia&gt;</code> element (which facilitates access to the user’s camera and/or microphone), and <code>&lt;camera&gt;</code> and <code>&lt;microphone&gt;</code> elements (which facilitates access to them individually).</p>
<p>All of these are being trialed in Chrome as part of a larger initiative to improve the process and experience of requesting permission, which is bloody great, in my opinion.</p>
        
        ]]></description>
        
      </item>
    
    </channel>
  </rss>
