Web Standards

Jetpack Turns 10!

Css Tricks - Tue, 04/06/2021 - 3:27am

(This is a sponsored post.)

Ten years! That’s a huge milestone for a project, especially one that had a pretty simple goal in mind from the start: give self-hosted WordPress sites many of the same features and functionality enjoyed by hosted WordPress.com sites.

It’s a great story. The Automattic team responsible for driving social activity in WordPress sees Jetpack as a way to expand and unify social activity across all WordPress sites, and winds up paving the way for a product that today helps more than 5 million sites with everything from security and performance to backups and integrations.

And what has Jetpack accomplished in those 10 years and 5 million sites? The numbers are staggering:

  • 122 billion blocked malicious login attempts.
    9,330,623 of those on CSS-Tricks, as we write.
  • 269 million site backups.
    Last backup of CSS-Tricks: 3 minutes ago, as we write.
  • 24 trillion images served by Jetpack CDN.
    Incredibly, a free feature of Jetpack.
  • 61.6 billion site searches.
    Try site search on this site, the latest release has really nice UI & UX improvements, like seeing the post thumbnail.
  • 50 billion related posts displayed. Related posts plugins are notoriously heavy on the server, but not when you let Jetpack do it!
  • 1.6 trillion tracked page views. Those are the numbers at work here with WordPress being some 40% of the web.
  • 2.6 billion shared social posts.
    The @css Twitter account runs itself thanks to Jetpack.

And you know CSS-Tricks is represented in those figures. Jetpack powers our search. We use it for real-time backups and downtime monitoring. It’s what helps us push content to Twitter and display related posts. We use its CDN. We even use a bunch of blocks it includes when we’re writing posts like this. We love Jetpack.

The Jetpack team launched a site celebrating 10 years. And, hey, for a super limited time, you can get 40% off the entire first year of any Jetpack plan.

Direct Link to ArticlePermalink

The post Jetpack Turns 10! appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Definition Tag

Css Tricks - Mon, 04/05/2021 - 5:54am

It’s <dfn>. Jen Kramer and Erika Lee are doing a #30DaysofHTML email list thing-y on Substack, which is an easy subscribe. It’s only been a few days and all of them have little gems, even for someone like me who likes to think he has a pretty decent grasp on HTML. Day 4 is <dfn>.

I’m sure I could have told you that <dfn> was “definition” but I certainly don’t reach for it as often as I probably should and couldn’t give you a straight answer on the perfect time to use it.

I think Erika nails that here:

<p>He is not as enamored with <dfn id="kong">King Kong</dfn> who resembles an enormous gorilla-like ape that has appeared in various media since 1933. </p> ... <p>Complaints about <a href="#kong">Kong</a> include how he has no atomic fire breath.</p>

I really like the idea of defining a term naturally and contextually within a block of text, and pointing back up to it with an anchor link later if needed.

Direct Link to ArticlePermalink

The post Definition Tag appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Creating a Smart Navbar With Vanilla JavaScript

Css Tricks - Mon, 04/05/2021 - 2:55am

Sticky, or fixed, navigation is a popular design choice because it gives users persistent access to navigate the site. On the other hand, it takes up space on the page and sometimes covers content is a way that’s less than appealing.

A possible solution? Smart navigation.

Let’s define “smart navigation” as:

  1. Visible at the top of the page
  2. Visible when the user moves up the page (wherever they may have scrolled to)
  3. Hidden when the user moves down the page

Here’s an example of how that might work:

CodePen Embed Fallback

It‘s all the convenience of sticky positioning, with an added fullscreen benefit. This sort of smart navigation is already commonly (think of the URL bar in many mobile browsers), but is sometimes a hassle to implement without a library or plugin. So, in this article, we’ll discuss how to build one using CSS and vanilla JavaScript.

Side note: People have different definitions of what scrolling down a page means (imagine how some trackpad preferences scroll the page up when you move your fingers down). For the purposes of this article, scrolling down refers to moving towards the bottom of the page.

Let’s look at the code

Here’s some example HTML. Our smart navigation will be the <nav> which sits above the <main>:

<nav> <div class="logo"> Logo </div> <div class="links"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> </div> </nav> <main> <!--Place the content of your page here--> </main>

It’s important to note that elements are only sticky relative to their parent container. The parent container of <nav> should be the body tag; it shouldn’t be placed within another tag on the page.

The CSS for our smart navigation looks like this:

nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; justify-content: space-between; padding: 1.5rem 2rem; background-color: #eaeaea; }

Now we need to detect when our user is scrolling the page and the direction of their scrolling. A user is scrolling down if the value of their last scroll position is less than the value of their current scroll position. Breaking the logic down, we’ll need to:

  1. Define a variable to store the previous scroll position
  2. Assign a variable to detect the current scroll position set to the scroll offset of the page

If the current scroll position is greater than the previous scroll position, then the user is scrolling downwards. Let’s call our function isScrollingDown:

let previousScrollPosition = 0; const isScrollingDown = () => { let currentScrolledPosition = window.scrollY || window.pageYOffset; let scrollingDown; if (currentScrolledPosition > previousScrollPosition) { scrollingDown = true; } else { scrollingDown = false; } previousScrollPosition = currentScrolledPosition; return scrollingDown; };

Here’s a visual representation of how this function works:

CodePen Embed Fallback

With this logic, we’re able to detect when the page is scrolling down so we can use this to toggle our nav styling:

const nav = document.querySelector('nav'); const handleNavScroll = () => { if (isScrollingDown()) { nav.classList.add('scroll-down'); nav.classList.remove('scroll-up') } else { nav.classList.add('scroll-up'); nav.classList.remove('scroll-down') } }

If the user is scrolling down, we’ll assign a .scroll-down class that contains our styling method for when the page is moving downward. We can update our <nav> CSS to this:

nav { /* default styling */ transition: top 500ms ease-in-out; } nav.scroll-up { top: 0; } nav.scroll-down { top: -100%; }

With this styling, the top property value of <nav> is set to -100% of the page height so it slides out of view. We could also choose to handle our styling with translate or by fading it out — whatever animation works best.

Performance

Whenever we’re working with scroll event listeners, performance is something that should immediately come to mind. Right now, we’re calling our function every time the user scrolls the page, but we don’t need to detect each pixel movement.

For this case, we can implement a throttle function instead. A throttle function is a higher order function that acts as a timer for the function passed into it. If we throttle a scroll event with a timer of 250ms, the event will only be called every 250ms while the user scrolls. It’s a great way to limit the number of times we call the function, helping with the performance of the page.

David Corbacho goes deeper into throttle implementations in this article.

A simple throttle implementation in JavaScript looks like this:

// initialize a throttleWait variable var throttleWait; const throttle = (callback, time) => { // if the variable is true, don't run the function if (throttleWait) return; // set the wait variable to true to pause the function throttleWait = true; // use setTimeout to run the function within the specified time setTimeout(() => { callback(); // set throttleWait to false once the timer is up to restart the throttle function throttleWait = false; }, time); }

Then we can include our handleNavScroll function inside a throttle:

window.addEventListener("scroll", () => { throttle(handleNavScroll, 250) });

With this implementation, the handleNavScroll function is only called once every 250ms.

Accessibility

Whenever implementing a custom feature in JavaScript, we must always take accessibility into concern. One such issue is ensuring that <nav> is visible when it’s in focus. Browsers tend to scroll to the part of the page that currently has focus by default, but there can be certain complications when working with scroll events.

A way to ensure that <nav> is always visible is to update the CSS to account for focus. Now our CSS looks like this:

nav.scroll-up, nav:focus-within { top: 0; }

Unfortunately, the focus-within selector isn’t fully supported across all browsers. We can include a JavaScript fallback for it:

const handleNavScroll = () => { if (isScrollingDown() && !nav.contains(document.activeElement))) { nav.classList.add('scroll-down'); nav.classList.remove('scroll-up') } else { nav.classList.add('scroll-up'); nav.classList.remove('scroll-down') } }

In this updated function, we only apply the scroll-down class if the user is scrolling down the page and the <nav> doesn’t currently have any element with focus in it.

Another aspect of accessibility is the consideration that some users may not want to have any animation on the page. That’s something we can detect and respect with the prefers-reduced-motion CSS media query. We can update this method in JavaScript and prevent our function from running at all if a user prefers reduced motion:

const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)"); window.addEventListener("scroll", () => { if (mediaQuery && !mediaQuery.matches) { throttle(handleNavScroll, 250) } }); Wrapping up

So, there we have it: a smart navigation implementation with plain CSS and vanilla JavaScript. Now users have persistent access to navigate the site without losing real estate in a way that blocks content.

Plus, the benefit of a custom implementation like this is that we get a delightful user experience that isn’t over-engineered or sacrifices open performance or accessibility.

CodePen Embed Fallback

The post Creating a Smart Navbar With Vanilla JavaScript appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Platform News: Rounded Outlines, GPU-Accelerated SVG Animations, How CSS Variables Are Resolved

Css Tricks - Fri, 04/02/2021 - 9:35am

In the news this week, Firefox gets rounded outlines, SVG animations are now GPU-accelerated in Chrome, there are no physical units in CSS, The New York Times crossword is accessible, and CSS variables are resolved before the value is inherited.

Let’s jump in the news!

Rounded outlines are coming to Firefox

The idea to have the outline follow the border curve has existed ever since it became possible to create rounded borders via the border-radius property in the mid 2000s. It was suggested to Mozilla, WebKit, and Chromium over ten years ago, and it’s even been part of the CSS UI specification since 2015:

The parts of the outline are not required to be rectangular. To the extent that the outline follows the border edge, it should follow the border-radius curve.

Fast-forward to today in 2021 and outlines are still rectangles in every browser without exception:

CodePen Embed Fallback

But this is finally starting to change. In a few weeks, Firefox will become the first browser with rounded outlines that automatically follow the border shape. This will also apply to Firefox’s default focus outline on buttons.

Please star Chromium Issue #81556 (sign in required) to help prioritize this bug and bring rounded outlines to Chrome sooner rather than later.

SVG animations are now GPU-accelerated in Chrome

Until recently, animating an SVG element via CSS would trigger repaint on every frame (usually 60 times per second) in Chromium-based browsers. Such constant repainting can have a negative impact on the smoothness of the animation and the performance of the page itself.

The latest version of Chrome has eliminated this performance issue by enabling hardware acceleration for SVG animations. This means that SVG animations are offloaded to the GPU and no longer run on the main thread.

In this example, the SVG circle is continuously faded in and out via a CSS animation (see code)

The switch to GPU acceleration automatically made SVG animations more performant in Chromium-based browsers (Firefox does this too), which is definitely good news for the web:

Hooray for more screen reader-accessible, progressively enhanced SVG animations and less Canvas.

There cannot be real physical units in CSS

CSS defines six physical units, including in (inches) and cm (centimeters). Every physical unit is in a fixed ratio with the pixel unit, which is the canonical unit. For example, 1in is always exactly 96px. On most modern screens, this length does not correspond to 1 real-world inch.

The FAQ page of the CSS Working Group now answers the question why there can’t be real physical units in CSS. In short, the browser cannot always determine the exact size and resolution of the display (think projectors). For websites that need accurate real-world units, the Working Group recommends per-device calibration:

Have a calibration page, where you ask the user to measure the distance between two lines that are some CSS distance apart (say, 10cm), and input the value they get. Use this to find the scaling factor necessary for that screen (CSS length divided by user-provided length).

This scaling factor can then be set to a custom property and used to compute accurate lengths in CSS:

html { --unit-scale: 1.428; } .box { /* 5 real-world centimeters */ width: calc(5cm * var(--unit-scale, 1)); } The Times crossword is accessible to screen reader users

The NYT Open team wrote about some of the improvements to the New York Times website that have made it more accessible in recent years. The website uses semantic HTML (<article>, <nav>, etc.), increased contrast on important components (e.g., login and registration), and skip-to-content links that adapt to the site’s paywall.

Furthermore, the Games team made the daily crossword puzzle accessible to keyboard and screen reader users. The crossword is implemented as a grid of SVG <rect> elements. As the user navigates through the puzzle, the current square’s aria-label attribute (accessible name) is dynamically updated to provide additional context.

The screen reader announces the clue, the number of letters in the solution, and the position of the selected square

You can play the mini crossword without an account. Try solving the puzzle with the keyboard.

CSS variables are resolved before the value is inherited

Yuan Chuan recently shared a little CSS quiz that I didn’t answer correctly because I wasn’t sure if a CSS variable (the var() function) is resolved before or after the value is inherited. I’ll try to explain how this works on the following example:

html { --text-color: var(--main-color, black); } footer { --main-color: brown; } p { color: var(--text-color); }

The question: Is the color of the paragraph in the footer black or brown? There are two possibilities. Either (A) the declared values of both custom properties are inherited to the paragraph, and then the color property resolves to brown, or (B) the --text-color property resolves to black directly on the <html> element, and then this value is inherited to the paragraph and assigned to the color property.

The correct answer is option B (the color is black). CSS variables are resolved before the value is inherited. In this case, --text-color falls back to black because --main-color does not exist on the <html> element. This rule is specified in the CSS Variables module:

It is important to note that custom properties resolve any var() functions in their values at computed-value time, which occurs before the value is inherited.

The post Platform News: Rounded Outlines, GPU-Accelerated SVG Animations, How CSS Variables Are Resolved appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Honeypot DEVS ANSWER

Css Tricks - Fri, 04/02/2021 - 9:34am

I did this thing for Honeypots YouTube Channel. I had heard of Honeypot through these mini documentaries they have done, like about Vue.js, GraphQL, and Ember.js. They do a great job, so I was happy to shoot them over some answers to questions for this series.

Here’s a TLDR-ish transcript:

What’s the best way to stay up to date with new technologies?

Don’t worry about it much. If you’re actively building websites and solving problems that come up day to day, you’re doing the job and that’s what’s important. If you’re really worried you’re only ever using outdated tech, go to a conference once a year and see what people are talking about.

What are your top tips for career advancement?

Writing! You don’t have to blog, even though I like that idea. You can write to your co-workers, or even keep a private log. Writing really opens doors and makes you a better thinker.

What strengths are most important for a developer?

Communication trumps raw technical skill. One developer alone can never do as much as a high functioning team, and communication is what makes a team high functioning.

What what the proudest moment of your career?

I tend to look back at things that took a long time and didn’t involve just me. CodePen will be 10 years old next year. That’s something to be proud of.

When did you realize you wanted to be a developer?

I had a good teacher in high school. I’m sure they don’t even remember me, but I was highly into the computer programming class they taught. I’d come to school early to use the computer lab. I’d stay after school. I’d take my study halls there. Working on a program, with the guidance of that teacher, was deeply fun. While I ended up abandoning computer science in college for art, my career now I find was a way to marry my love of computer nerdery and art.

The post Honeypot DEVS ANSWER appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

The Deno Company

Css Tricks - Fri, 04/02/2021 - 9:10am

I’m sure a lot of you are paying attention to Deno anyway, the next-gen JavaScript-on-the-sever project from Node creator Ryan Dahl, especially after dropping all these candid regrets about what happened in Node. But perhaps you’re paying more attention now that Deno has taken some seed investment and will be turning itself into a company, while staying open-source:

For Deno to grow and be maximally useful, it must remain permissively free. We don’t believe the “open core” business model is right for a programming platform like Deno. We do not want to find ourselves in the unfortunate position where we have to decide if certain features are for paid customers only. If you watch our conference talks, you will find we’ve been hinting at commercial applications of this infrastructure for years. We are bullish about the technology stack we’ve built and intend to pursue those commercial applications ourselves. Our business will build on the open source project, not attempt to monetize it directly.

I’m excited about this because other people are, to some degree. I know the “secure by default” nature of it is exciting to my extremely security-conscious co-founder, Alex.

I find features like “TypeScript out of the box” interesting. While I don’t really use TypeScript myself, I find it striking just what a big deal it is. Talking to Laurie Voss a few years back, I learned that nearly two-thirds of developers were using it, and it doesn’t seem like it has lost any steam. And you’ve got Scott Tolinski over here waxing poetic about how GraphQL is all typed and you get this dreamy fully-typed stack when TypeScript is part of the mix.

There is already a bundler (literally, Bundler) for Deno that supports TypeScript out of the box, along with JSX. Guess what else does? The big next-gen build tools, Snowpack, Vite, and wmr.

Deno is also written in Rust, which is an interesting angle to all this, partially because of the speed (it’s fast). Snowpack and Vite both use esbuild under the hood, which is written in Go (also fast). I don’t have a great sense of whether Go or Rust is faster for this type of work, but they are both a big leap forward from most of the bundlers and task runners we use today. You can even use esbuild directly, or with light abstractions over it, like Estrella. Again, TypeScript supported.

It makes me wonder about Babel. If you don’t run TypeScript through it, and don’t need it for JSX, and don’t need to compile away basic ES6/7 stuff now that support is so wide, how long does it stick around? A long time, is the answer, of course. A project as big as Babel doesn’t just disappear. I suppose all it takes is one exotic and desirable new JavaScript feature that is compilable to an existing syntax, and everybody will be putting it back into their pipelines.

The post The Deno Company appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Click Outside Detector

Css Tricks - Fri, 04/02/2021 - 4:49am

It’s a reasonable UX thing that you can click-to-open something, and then not only be able to click that same thing to close it, but click outside the thing that it opened to close it. Kitty Giraudel just blogged about that. The trick is that once the thing is opened, you attach an event handler to the window with that watches for events (like another click). If that subsequent click did not happen within the newly-opened area, close it. Like, literally thing.contains(event.target). It’s a nice trick, I think.

There are lots of little things to think about though. For example:

we have to stop the propagationg of the click event on the toggle itself. Otherwise, it goes up to the window click listener, and since the toggle is not contained within the menu, it would close the latter as soon as we try to open it.

Right right. Can’t have that or it breaks the whole thing.

We have this same pattern in a lot of places on CodePen. Like Kitty, we have it implemented in React. In taking a peek at our implementation, it’s got a number of bells-and-whistles I figured were worth mentioning. For example, ours isn’t a function or hook, but a component wrapper we use like:

<ClickOutsideDetector listen onClickOutside={() => { closeTheThing(); }} > A Menu or Modal or something. </ClickOutsideDetector>

That way it is a generic wrapper that we can use for anything on a “click outside”. The bells-and-whistles being:

  • You can pass in component prop so that it doesn’t have to manifest as a <div> but whatever you want it to be semantically.
  • The listen prop allows you to toggle if it is currently actively listening to events. Like a quick way to short-circuit it.
  • An ESC keypress is the functional equivalent to clicking outside.
  • Handles touch events as well as clicks
  • Handles a case where the click outside happens into an <iframe> in which case the window has a blur event rather than a click.
  • Allows you to pass in elements to ignore, so rather than the stopPropagation trick that Kitty documented, we can be specific about elements that don’t trigger a click outside.

So many little things! To me this is the kinda perfect little example of real-world development. You just want one little behavior and ultimately there are a ton of considerations and edge cases you have to deal with and it’s never really done. I just touched our component in the last few months because of a third-party tool we used changed how they did something which affected iframes in use on the page. Ultimately I had to watch for a blur event that then check the classList of document.activeElement to see if that was the thing eating the click outside!

Annnnyway, I tossed up a only-slightly-dumbed-down version of ours here.

And I saw something from Kitty’s post that we weren’t handling, and it’s in the very first sentence:

we needed a way to close the menu when clicking outside of it or tabbing out of it.

Emphasis mine. Don’t worry, I’ve got a TODO in our code for that now.

The post Click Outside Detector appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

WordPress Caching: All You Need To Know

Css Tricks - Thu, 04/01/2021 - 11:21am

Here’s Ashley Rich at Delicious Brains writing about all the layers of caching that are relevant to a WordPress site. I think we all know that caching is complicated, but jeez, it’s a journey to understand all the caches at work here. The point of cache being speed and reducing burden on the worst bottlenecks and slowest/busiest parts of a web stack.

Here’s my own understanding:

  • Files can be cached by the browser. This is the fastest possible cache as no network request happens at all. Assets like images, CSS, and JavaScript are often cached this way because they don’t change terribly frequently, but you have to make sure you’re telling browsers that it’s OK to do this and have a mechanism in place to break that cache if you need to (e.g. by changing file names). You very rarely cache the HTML this way, as it changes the most and file-name-cache-busting of HTML seems more tricky than it’s worth.
  • Files can be cached at the CDN level. This is great because even though network traffic is happening, CDN servers are very fast and likely geographically closer to users than your origin server. If users get files from here, they never even trouble your origin server. You’ll need a way to break this cache as well, which again is probably through changing file names. You might cache HTML at this level even without changing file names if you have a mechanism to clear that cache globally when content changes.
  • The origin server might cache built HTML pages. On a WordPress site, the pages are built with PHP which probably triggers MySQL queries. If the server can save the result of the things that have already executed, that means it can serve a “static” file as a response, which it can do much faster than having to run the PHP and MySQL. That’ll work for logged out users, who all get the same response, but not for logged in users who have dynamic content on the page (like the WordPress admin bar).
  • The database has its own special caching. After a MySQL query is executed, the results can be saved in an Object Cache, meaning the same request can come from that cache instead of having to run the query again. You get that automatically to some degree, but ideally it gets wired up to a more persistent store, which you do not get automatically

Phew. It gets a little easier with Jamstack since your pages are prebuilt and CDN-hosted already, and in the case of Netlify, you don’t even have to worry about cache busting.

But even as complex as this is, I don’t worry about it all that much. This WordPress site uses Flywheel for hosting which deals with the database and server-level caching, I have Cloudflare in front of it with special WordPress optimization for the CDN caching, and roll-my-own file-name cache busting (I wish this part was easier). I’d certainly trust SpinupWP to get it right too, given Ashley’s great writeup I’m linking to here.

Direct Link to ArticlePermalink

The post WordPress Caching: All You Need To Know appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

React Authentication & Access Control

Css Tricks - Thu, 04/01/2021 - 11:20am

Authentication and access control are required for most applications, but they often distract us from building core features. In this article, I’ll cover a straightforward way to add auth and access control in React.

Instead of adding a static library that you have to keep up to date or re-research each time you build a project, we’ll use a service that stays up to date automatically and is a much simpler alternative to Auth0, Okta, and others.

React authentication

There are two main things your React application needs to do to sign on a user:

  1. Get an access token from an authentication server
  2. Send the access token to your backend server with each subsequent request

These steps are the same for pretty much all authentication, whether that’s standard email and password, magic links, or single sign on (SSO) providers like Google, Azure, or Facebook.

Ultimately, we want our React app to send an initial request to an authentication server and have that server generate an access token we can use.

JWT access tokens

There are different choices for what type of access token to use, and JSON Web Tokens (JWTs) are a great option. JWTs are compact, URL-safe tokens that your React application can use for authentication and access control.

Each JWT has a JSON object as its “payload” and is signed such that your backend server can verify that the payload is authentic. An example JWT looks like:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImF1dGhvcml6YXRpb24iOiJhZG1pbiJ9.f7iKN-xi24qrQ5NQtOe0jiriotT-rve3ru6sskbQXnA

The payload for this JWT is the middle section (separated by periods):

eyJ1c2VySWQiOjEsImF1dGhvcml6YXRpb24iOiJhZG1pbiJ9

The JWT payload can be decoded from base64 to yield the JSON object:

JSON.parse(atob("eyJ1c2VySWQiOjEsImF1dGhvcml6YXRpb24iOiJhZG1pbiJ9")); // => { “userId”: 1, “authorization”: “admin” }

It’s important to note that this payload is readable by anyone with the JWT, including your React application or a third party. Anyone that has the JWT can read its contents.

However, only the authentication server can generate valid JWTs. Your React application, your backend server, or a malicious third party cannot generate valid JWTs, only read and verify them.

When your backend server receives a request with a JWT, it should verify the JWT as authentic by checking it against the public key for that JWT. This allows your application server to verify incoming JWTs and reject any tokens that were not created by the authentication server (or that have expired).

The flow for using a JWT in your React application looks like this:

  1. Your React app requests a JWT from the authentication server whenever the user wants to sign on.
  2. The authentication server generates a JWT using a private key and then sends the JWT back to your React app.
  3. Your React app stores this JWT and sends it to your backend server whenever your user needs to make a request.
  4. Your backend server verifies the JWT using a public key and then reads the payload to determine which user is making the request.

Each of these steps is simple to write down, but each step has its own pitfalls when you actually want to implement it and keep it secure. Especially over time, as new threat vectors emerge and new platforms need to be patched or supported, the security overhead can add up quickly.

Userfront removes auth complexity in React apps

Userfront is a framework that abstracts away auth complexity. This makes it much easier for you to work with authentication in a React application and, perhaps most importantly, it keeps all the auth protocols updated for you automatically over time.

The underlying philosophy with Userfront is that world-class auth should not take effort – it should be easy to set up, and security updates should happen for you automatically. Userfront has all the bells and whistles of authentication, Single Sign On (SSO), access control, and multi-tenancy, with a production-ready free tier up to 10,000 monthly active users.

For most modern React applications, it’s a great solution.

Setting up authentication in React

Now we’ll go through building all the main aspects of authentication in a React application. The final code for this example is available here.

Set up your React application and get your build pipeline in order however you prefer. In this tutorial, we’ll use Create React App, which does a lot of the setup work for us, and we’ll also add React Router for client-side routing. Start by installing Create React App and React Router:

npx create-react-app my-app cd my-app npm install react-router-dom --save npm start

Now our React application is available at http://localhost:3000.

Like the page says, we can now edit the src/App.js file to start working.

Replace the contents of src/App.js with the following, based on the React Router quickstart:

// src/App.js import React from "react"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; export default function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/login">Login</Link> </li> <li> <Link to="/reset">Reset</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> </ul> </nav> <Switch> <Route path="/login"> <Login /> </Route> <Route path="/reset"> <PasswordReset /> </Route> <Route path="/dashboard"> <Dashboard /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return <h2>Home</h2>; } function Login() { return <h2>Login</h2>; } function PasswordReset() { return <h2>Password Reset</h2>; } function Dashboard() { return <h2>Dashboard</h2>; }

Now we have ourselves a very simple app with routing:

RouteDescription/Home page/loginLogin page/resetPassword reset page/dashboardUser dashboard, for logged in users only

This is all the structure we need to start adding authentication.

Signup, login, and password reset with Userfront

Go ahead and create a Userfront account. This will give you a signup form, login form, and password reset form you can use for the next steps.

In the Toolkit section of your Userfront dashboard, you can find the instructions for installing your signup form:

Follow the instructions by installing the Userfront React package with:

npm install @userfront/react --save npm start

Add the signup form to your home page by importing and initializing Userfront, and then updating the Home() function to render the signup form.

// src/App.js import React from "react"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Userfront from "@userfront/react"; Userfront.init("demo1234"); const SignupForm = Userfront.build({ toolId: "nkmbbm", }); export default function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/login">Login</Link> </li> <li> <Link to="/reset">Reset</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> </ul> </nav> <Switch> <Route path="/login"> <Login /> </Route> <Route path="/reset"> <PasswordReset /> </Route> <Route path="/dashboard"> <Dashboard /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return ( <div> <h2>Home</h2> <SignupForm /> </div> ); } function Login() { return <h2>Login</h2>; } function PasswordReset() { return <h2>Password Reset</h2>; } function Dashboard() { return <h2>Dashboard</h2>; }

Now the home page has your signup form. Try signing up a user:

Your signup form is in “Test mode” by default, which will create user records in a test environment you can view separately in your Userfront dashboard:

Continue by adding your login and password reset forms in the same way that you added your signup form:

// src/App.js import React from "react"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Userfront from "@userfront/react"; Userfront.init("demo1234"); const SignupForm = Userfront.build({ toolId: "nkmbbm", }); const LoginForm = Userfront.build({ toolId: "alnkkd", }); const PasswordResetForm = Userfront.build({ toolId: "dkbmmo", }); export default function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/login">Login</Link> </li> <li> <Link to="/reset">Reset</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> </ul> </nav> <Switch> <Route path="/login"> <Login /> </Route> <Route path="/reset"> <PasswordReset /> </Route> <Route path="/dashboard"> <Dashboard /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return ( <div> <h2>Home</h2> <SignupForm /> </div> ); } function Login() { return ( <div> <h2>Login</h2> <LoginForm /> </div> ); } function PasswordReset() { return ( <div> <h2>Password Reset</h2> <PasswordResetForm /> </div> ); } function Dashboard() { return <h2>Dashboard</h2>; }

At this point, your signup, login, and password reset should all be functional.

Your users can sign up, log in, and reset their password.

Access control in React

Usually, we don’t want users to be able to view the dashboard unless they are logged in. This is known as a protected route.

Whenever a user is not logged in but tries to visit /dashboard, we can redirect them to the login screen.

We can accomplish this by updating the Dashboard component in src/App.js to handle the conditional logic.

When a user is logged in with Userfront, they will have an access token available as Userfront.accessToken(). We can check for this token to determine if the user is logged in. If the user is logged in, we can show the dashboard page, and if the user is not logged in, we can redirect to the login page.

Add the Redirect component to the import statement for React Router, and then update the Dashboard component to redirect if no access token is present.

// src/App.js import React from "react"; import { BrowserRouter as Router, Switch, Route, Link, Redirect, // Be sure to add this import } from "react-router-dom"; // ... function Dashboard() { function renderFn({ location }) { // If the user is not logged in, redirect to login if (!Userfront.accessToken()) { return ( <Redirect to={{ pathname: "/login", state: { from: location }, }} /> ); } // If the user is logged in, show the dashboard const userData = JSON.stringify(Userfront.user, null, 2); return ( <div> <h2>Dashboard</h2> <pre>{userData}</pre> <button onClick={Userfront.logout}>Logout</button> </div> ); } return <Route render={renderFn} />; }

Notice also that we’ve added a logout button by calling Userfront.logout() directly:

<button onClick={Userfront.logout}>Logout</button>

Now, when a user is logged in, they can view the dashboard. If the user is not logged in, they will be redirected to the login page.

React authentication with an API

You’ll probably want to retrieve user-specific information from your backend. In order to protect your API endpoints, your backend server should check that incoming JWTs are valid.

There are many libraries available to read and verify JWTs across various languages; here are a few popular libraries for handling JWTs:

Node.js.NETPythonJava Your access token

While the user is logged in, their access token is available in your React application as Userfront.accessToken().

Your React application can send this as a Bearer token inside the Authorization header to your backend server. For example:

// Example of calling an endpoint with a JWT import Userfront from "@userfront/react"; Userfront.init("demo1234"); async function getInfo() { const res = await window.fetch("/your-endpoint", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${Userfront.accessToken()}`, }, }); console.log(res); } getInfo();

To handle a request like this, your backend should read the JWT from the Authorization header and verify that it is valid using the public key found in your Userfront dashboard.

Here is an example of Node.js middleware to read and verify the JWT access token:

// Node.js example (Express.js) const jwt = require("jsonwebtoken"); function authenticateToken(req, res, next) { // Read the JWT access token from the request header const authHeader = req.headers["authorization"]; const token = authHeader && authHeader.split(" ")[1]; if (token == null) return res.sendStatus(401); // Return 401 if no token // Verify the token using the Userfront public key jwt.verify(token, process.env.USERFRONT_PUBLIC_KEY, (err, auth) => { if (err) return res.sendStatus(403); // Return 403 if there is an error verifying req.auth = auth; next(); }); }

Using this approach, any invalid or missing tokens would be rejected by your server. You can also reference the contents of the token later in the route handlers using the req.auth object:

console.log(req.auth); // => { mode: 'test', tenantId: 'demo1234', userId: 5, userUuid: 'ab53dbdc-bb1a-4d4d-9edf-683a6ca3f609', isConfirmed: false, authorization: { demo1234: { tenantId: 'demo1234', name: 'Demo project', roles: ["admin"], permissions: [] }, }, sessionId: '35d0bf4a-912c-4429-9886-cd65a4844a4f', iat: 1614114057, exp: 1616706057 }

With this information, you can perform further checks as desired, or use the userId or userUuid to look up user information to return.

For example, if you wanted to limit a route to admin users only, you could check against the authorization object from the verified access token, and reject any tokens that don’t have an admin role:

// Node.js example (Express.js) app.get("/users", (req, res) => { const authorization = req.auth.authorization["demo1234"] || {}; if (authorization.roles.includes("admin")) { // Allow access } else { // Deny access } }); React SSO (Single Sign On)

With your Toolkit forms in place, you can add social identity providers like Google, Facebook, and LinkedIn to your React application, or business identity providers like Azure AD, Office365, and more.

You do this by creating an application with the identity provider (e.g. Google), and then adding that application’s credentials to the Userfront dashboard. The result is a modified sign on experience:

No additional code is needed to implement Single Sign On using this approach: you can add and remove providers without updating your forms or the way you handle JWTs.

Final notes

React authentication and access control can be complex to do yourself, or it can be simple when using a service.

Both the setup step and, more importantly, the maintenance over time, are handled with modern platforms like Userfront.

JSON Web Tokens allow you to cleanly separate your auth token generation layer from the rest of your application, making it easier to reason about and more modular for future needs. This architecture also allows you to focus your efforts on your core application, where you are likely to create much more value for yourself or your clients.

For more details on adding auth to your React application, visit the Userfront guide, which covers everything from setting up your auth forms to API documentation, example repositories, working with different languages and frameworks, and more.

Create a free Userfront project

The post React Authentication & Access Control appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Designing calculator apps

Css Tricks - Thu, 04/01/2021 - 4:23am

It is extremely weird that the calculator apps, even the default ones baked into desktop operating systems, embrace the UI and UX of those little cheap-o plastic physical calculators. I like what Florens Verschelde’s Math teacher had to say:

I had a Math teacher who would ban pocket calculators that didn’t show both your input and its result at the same time. If a calculator couldn’t show this:

38 ÷ 1.2 = 31.666666666667

You couldn’t use it.

The article ends up being in praise of Soulver, which I agree is a nice modern take on the idea of calculations.

I wish it was on Setapp, as I’d probably use it. But I don’t do enough regular mathin’ to go for the full price (today, anyway).

Direct Link to ArticlePermalink

The post Designing calculator apps appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Where the World Wide Web Shines

Css Tricks - Wed, 03/31/2021 - 12:17pm

Here’s a fabulous post by Vitaly Friedman that looks at how to make accessible front-end components and what problems there are today when it comes to building them.

There’s so much great info packed into this one post that I’m going to keep it open in a tab for quite some time. But I have two thoughts here. First, just skimming through the article is enough to make anyone realize that accessibility is a complex subject and it’s so very easy to get things wrong; colors, images, text, HTML, mouse pointer vs. touch, small screens vs. large screens, charts and data viz, form components, layout and semantic ordering. The list goes on and on. It’s clear to me now (and I am late to the party) that accessibility is a full-time job.

Second, Vitaly makes note of some of the excellent work that the Government Digital Service (GDS) is doing in the UK by releasing open-source components such as accessible-autocomplete. And I have to say, I think the work that GDS is doing is so very inspiring to me as a web designer and developer.

Here’s a story: a few years ago I had to book an appointment to get a driver’s license. I hopped on the website and, immediately, I recognized that it was using the GDS design system. That gave me a great sigh of relief, but then I found myself sailing through this form at lightning speed. By the end, I realized that this is what every website should feel like; I used the site, did what I needed to do as quickly as possible, and then left.

It was one of the most shocking experiences for me as a web designer because there was no cruft, no junk, and no messing around with the experience in any way. It was fast, didn’t break down, crash the browser, or confuse me at all. The form inputs were big and clickable and the correct keyboard was selected when I viewed it on my phone. All of this accessibility work that they’ve poured into making things just work is a joyous thing.

This reminds me of something that Jeremy Keith wrote about the other day when he used another government website to get vaccinated:

[…] it’s a sequence of short forms, clearly labelled. Semantic accessible HTML, some CSS, and nothing more. If your browser doesn’t support JavaScript (or you’ve disabled it for privacy reasons), that won’t make any difference to your experience. This is the design system in action and it’s an absolute pleasure to experience.

[…] Maybe I’ll never need to visit that URL again. In the case of the NHS, I hope I won’t need to visit again. I just need to get in, accomplish my task, and get out again. This is where the World Wide Web shines.

Direct Link to ArticlePermalink

The post Where the World Wide Web Shines appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Overlay Fact Sheet

Css Tricks - Wed, 03/31/2021 - 10:36am

I would hope all our web designer/developer spidey senses trigger when the solution to an accessibility problem isn’t “fix the issue” but rather “add extra stuff to the page.” This Overlay Fact Sheet website explains that. An “Overlay” is one of those “add extra stuff to the page” things, ostensibly for improving accessibility. Except, even though marketing may suggest they are a silver bullet to accessibility, they are… not.

The site does a much better job laying that out than I can, so go check it out. As I write, it’s signed by 352 people, mostly people who are accessibility professionals.

Direct Link to ArticlePermalink

The post Overlay Fact Sheet appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

This Web Site is a Tech Talk

Css Tricks - Wed, 03/31/2021 - 4:27am

This literal tech talk (YouTube video embedded in there) by Zach Leatherman is a good time. The talk is sprinkled with fun trickery, so I’m just taking notes on some on it here:

  • I have no idea how he pulled off the “bang on the keyboard and get perfect code” thing, but it reminds me of Jake Albaugh’s “Self-Coding” Pens.
  • Adding contenteditable on the <body> makes the whole page editable! Did you know document.designMode = "on" does the same thing in JavaScript? (More on making DevTools a design tool.)
  • There’s a short bit where the typing happens in two elements at once. CodePen supports that! Just CMD + click into the editor where you want another one to be, or make it part of a snippet.
  • System fonts are nice. I like how easy they are to invoke with system-ui. Firefox doesn’t seem to support that, so I guess we need the whole stack. I wonder how close we are to just needing that one value. Iain Bean has more on this in his “System fonts don’t have to be ugly” post.
  • box-decoration-break is a nice little touch for “inline headers.” The use of @supports here makes great sense as it’s not just that one property in use, but several. So, in a non-support situation, you’d want to apply none of it.
  • Slapping a <progress> in some <li> elements to compare rendering strategies is a neat way to get some perfect UI without even a line of CSS.
  • Making 11ty do syntax highlighting during the build process is very cool. I still use Prism.js on this site, which does a great job, but I do it client-side. I really like how this 11ty plugin is still Prism under the hood, but just happens when the page is built. I’d love to get this working here on this WordPress site, which I bet is possible since our code block in the block editor is a custom JavaScript build anyway.
  • In the first bullet point, I wrote that I had no idea how Zach did the “bang on the keyboard and get perfect code” but if you watch the bit about syntax highlighting and keep going, Zach shows it off and it’s a little mind spinning.

I think Zach’s overall point is strong: we should question any Single-Page-App-By-Default website building strategy.

As a spoonful of baby bear porridge here, I’d say I’m a fan of both static site generators and JavaScript frameworks. JavaScript frameworks offer some things that are flat-out good ideas for building digital products: components and state. Sometimes that means that client-side rendering is actually helpful for the interactivity and overall feel of the site, but it’s unfortunate when client-side rendering comes along for the ride by default instead of as a considered choice.

Direct Link to ArticlePermalink

The post This Web Site is a Tech Talk appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

ShopTalk Patreon

Css Tricks - Tue, 03/30/2021 - 10:29am

Dave and I launched a Patreon for ShopTalk Show. You get two completely priceless things for backing us:

  1. That great feeling you’re supporting the show, which has costs like editing, transcribing, developing, and hosting.
  2. Access to our backer-only Discord.

I think the Discord might be my favorite thing we ever done. Sorry if I’m stoking the FOMO there, but just saying, it’s a good gang. My personal intention is to be helpful in there, but everyone else is so helpful themselves that I’ve actually learned more than I’ve shared.

The Patreon is Here

Direct Link to ArticlePermalink

The post ShopTalk Patreon appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

You want margin-inline-start

Css Tricks - Tue, 03/30/2021 - 4:24am

David Bushell in ”Changing CSS for Good“:

I’m dropping “left“ and “right“ from my lexicon. The new CSS normal is all about Logical Properties and Values […] It can be as easy as replacing left/right with inline start/end. Top/bottom with block start/end. Normal inline flow, Flexbox, and Grid layouts reverse themselves automatically.

I figured it made sense as a “You want…” style post. Geoff has been documenting these properties nicely in the Almanac.

The post You want margin-inline-start appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Deliver Enhanced Media Experiences With Google’s Core Web Vitals

Css Tricks - Tue, 03/30/2021 - 4:23am

Hello! Satarupa Chatterjee from Cloudinary. There is a big change coming from Google in May 2021 having to do with their Core Web Vitals (CWVs). It’s worth paying attention here, as this is going to be a SEO factor.

I recently spoke with Tamas Piros about CWVs. The May 2021 update will factor in CWVs, along with other factors like mobile-friendliness and safe browsing, to generate a set of benchmarks for search rankings. Doubtless, the CWVs will directly affect traffic for websites and apps alike. Tamas is a developer-experience engineer at Cloudinary, a media-optimization expert, and a Google developer-expert in web technologies and web performance.

Here’s a written version of the video above, where the questions (Qs) are me, Satarupa, asking and Tamas answering (As).

Q: How did Google arrive at the three Core Web Vitals and their values?

A: As a dominant force in the search space, Google has researched in depth what constitutes a superb user experience, arriving at three important factors, which the company calls, collectively, the Core Web Vitals.

Before explaining them, I’d like to recommend an informative article, published last May on the Chromium Blog, titled The Science Behind Web Vitals. At the bottom of the piece are links to papers on the research that led to the guidelines for accurately evaluating user experiences.

Now back to the three Core Web Vitals. The first one affects page-load speed, which Google calls Largest Contentful Paint (LCP) with a recommendation of 2.5 seconds or less for the largest element on a page to load.

The second metric is First Input Delay (FID), which is a delta between a user trying to interact with a page, and the browser effectively executing that action. Google recommends 100 milliseconds or less. 

The third and last metric is Cumulative Layout Shift (CLS), which measures how stable a site is while it’s loading or while you’re interacting with it. In other words it is a measurement of individual layout shifts as well as unexpected layout shifts that happen during the lifespan of a page. The calculation involves impact and distance fractions which are multiplied together to give a final value. Google advocates this value to be 0.1 or less.

Q: How do the Core Web Vitals affect e-commerce?

A: Behind the ranking of Google search results are many factors, such as whether you use HTTPS and how you structure your content. Let’s not forget that relevant and well-presented content is as important as excellent page performance. The difference that core web vitals will make cannot be overstated. Google returns multiple suggestions for every search, however remember that good relevance is going to take priority. In other words good page experience will not override having great relevant content For example, if you search for Cloudinary, Google will likely show the Cloudinary site at the top of the results page. Page experience will become relevant when there are multiple available results, for a more generic search such as ‘best sports car’. In this case Google establishes that ranking based on the page’s user experience, too, which is determined by the Core Web Vitals.

Q: What about the other web vitals, such as the Lighthouse metrics? Do they still matter?

A: Businesses should focus primarily on meeting or staying below the threshold of the Core Web Vitals. However, they must also keep in mind that their page load times could be affected by other metrics, such as the length of time the first purchase takes and the first contentful paint.

For example, to find out what contributes to a bad First Input Delay—the FID, check the total blocking time and time to interact. Those are also vitals, just not part of the Core Web Vitals. You can also customize metrics with the many robust APIs from Google.. Such metrics could prove to be invaluable in helping you identify and resolve performance issues.

Q: Let’s talk about the Largest Contentful Paint metric, called LCP. Typically, the heaviest element on a webpage or in an app is an image. How would you reduce LCP and keep it below the Google threshold of 2.5 seconds?

A: What’s important to remember with regards to LCP is that we are talking about the largest piece of content that gets loaded on a page, and that is visible in the viewport (that is, it’s visible above the fold). Due to popular UX design patterns it’s likely that the largest, visible element is a hero image.

Google watches for <img> elements as well as <image> elements inside an SVG element. Video elements are considered too but only if they contain a poster attribute. Also of importance to Google are block-level elements, such as text-related ones like <h1>, <h2>, etc., and <span>.

All that means that you must load the largest piece of content as fast as possible. If your LCP is a hero image, be sure to optimize it—but without degrading the visual effects. Check out Cloudinary’s myriad effective and intuitive options for optimization. If you can strike a good balance between the file size and the visual fidelity of your image, your LCP will shine. 

Q: Suppose it’s now May 2021. What’s the likely effect of Google’s new criteria for search rankings for an e-commerce business that has surpassed the thresholds of all three or a couple of the Core Web Vitals?

A: According to Google, sites that meet the thresholds of the Core Web Vitals enjoy a 24-percent lower abandonment rate. The more you adhere to Google’s guidelines, the more engaging your site or app becomes and the faster your sales will grow. Needless to say, an appealing user experience attracts visitors and retains them, winning you an edge over the competition. Of course bear in mind the other search optimization guidelines set out by Google.

Again, be sure to optimize images, especially the most sizable one in the viewport, so that they load as fast as possible.

Q:  It sounds like e-commerce businesses should immediately start exploring ways to meet or better the vitals’ limits. Before we wrap up, what does the future look like for Core Web Vitals?

A: Late last year, Google held a conference and there were multiple talks touching upon this exact subject. All major changes will go into effect on a per-year basis, and Google has committed to announcing them well in advance.

Behind the scenes, Google is constantly collecting data from the field and checking them against user expectations. The first contentful paint, which I mentioned before, is under consideration as another Core Web Vital. Also, Google is thinking about reducing the yardstick for the First Input Delay metric—the FID, remember?—from 100 milliseconds to 75 or even 50.

Beyond that, Google has received a lot of feedback about some of the Core Web Vitals not working well for single-page apps. That’s because those apps are loaded only once. Even if they score an ideal Cumulative Layout Shift—that’s CLS—as you click around the page, things might move around and bring down the score. Down the road, Google might modify CLS to better accommodate single-page apps. 

Also on Google’s radar screen are metrics for security, privacy, and accessibility. Google promises to fine-tune the current metrics and launch new ones more frequently than major releases, including the introduction of new Core Web Vital metrics. 

So, change is the only constant here. I see a bright future for the vitals and have no doubt that we’re in good hands. Remember that Google vigilantly collects real user data as analytics to help figure out the appropriate standards. As long as you keep up with the developments and ensure that your site or app comply with the rules, you’ll get all greens throughout the scoreboard. That’s a great spot to be in.

Cloudinary offers myriad resources on media experience (MX), notably the MX Matters podcast, which encompasses experts’ take on the trends in today’s visual economy along with bulletins on new products and enhancements. Do check them out.

The post Deliver Enhanced Media Experiences With Google’s Core Web Vitals appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

:where() has a cool specificity trick, too.

Css Tricks - Mon, 03/29/2021 - 2:09pm

There is a lot of hype on the :is() pseudo-selector lately, probably because now that Safari 14 has it, it’s supported across all the major browsers. You’ve got Miriam tweeting about it, Kevin Powell doing a video, Šime getting it into the Web Platform News, and Robin mentioning it. Bramus really puts a point on it with these “three important facts”:

1. The selector list of :is() is forgiving
2. The specificity of :is() is that of its most specific argument
3. :is() does not work with pseudo-element selectors (for now)

Plus, of course, it’s main functionality which is making otherwise rather verbose, complex, and error-prone selectors easier to write. The specificity thing is extra-interesting. Miriam notes some trickery you could do with it, like juicing up specificity without actually selecting anything.

Say you wanted to use the .button class to select, but give it a ton of specificity

:is(.button, #increase#specificity) { /* specificity is now (0, 1, 0, 0) instead of (0, 0, 1, 0) }

I’ve done silly stuff like this in the past:

.button.button.button { /* forcing the selector to be (0, 0, 3, 0) instead of (0, 0, 1, 0) */ /* doesn't actually require element to have three button classes lol */ }

The :is() trick seems a little more understandable to me.

But what if you want to go the other way with specificity and lower it instead? Well, that’s the whole point of the :where() pseudo-selector. Functionally, it’s exactly the same as :is(). You give it a comma-separated list of things to select as part of the selector chain, and it does, with the same forgiving nature. Except, the specificity of the entire :where() part is zero (0).

Kevin showed off an interesting gotcha with :is() in the video:

.card :is(.title, p) { color: red; } .card p { color: yellow; }

You might think yellow will win out here, but the presence of .title in that :is() selector on top makes the specificity of that selector (0, 0, 2, 0) winning out over the (0, 0, 1, 1) below.

This is where we could consider using :where() instead! If we were to use the :where() pseudo-selector instead:

.card :where(.title, p) { color: red; } .card p { color: yellow; }

Then yellow would win, because the top selector lowers to (0, 0, 1, 0) specificity, losing to the bottom selector’s (0, 0, 1, 1).

Which one should you use? Ya know what, I’m not really sure if there is super solid time-tested advice here. At least we have both options available, meaning if you get into a pickle, you’ve got tools to use. Time has taught me that keeping specificity low is generally a healthier place to be. That gives you room to override, where if you’re riding high with specificity you have fewer options. But the zero specificity of :where() is pretty extreme and I could see that leading to confusing moments, too. So my gut is telling me you might wanna start with :is(), unless you notice you need to mix in a higher-specificity selector; if you do, back off to :where().

The post :where() has a cool specificity trick, too. appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Tricking CWV

Css Tricks - Mon, 03/29/2021 - 12:58pm

Google has said that Core Web Vitals (CWV) are going to be an SEO factor, and the date is nigh: May 2021. So, I’m seeing some scrambling to make sure those metrics are good. Ya know, the acronym soup: CLS, LCP, and FID. There is starting to be more and more tooling to measure and diagnose problems. Hopefully, once diagnosed, you have some idea how to fix them. Like if you have crappy CLS, it’s because you load in stuff (probably ads) that shifts layout, and you should either stop doing that or make space for them ahead of time so there is less shifting.

But what about LCP? What if you have this big hero image that is taking a while to paint and it’s giving you a crappy LCP number? Chris Castillo’s trick is to just not load the hero background image at all until a user interacts in some way. Strikes me as weird, but Chris did some light testing and found some users didn’t really notice:

Although this accomplishes the goal, it’s not without a cost. The background image will not load until the user interacts with the screen, so something needs to be used as a fallback until the image can be loaded. I asked a few friends to load the page on their phones and tell me if they found anything strange about the page, and none of them noticed anything “off”. What I observed is that the few friends I asked to test this all had their fingers on the screen or quickly touched the screen when the page was loading, so it happened so quickly they didn’t notice. 

It’s a fine trick that Chris documents, but the point is fooling a machine into giving you better test scores. This feels like the start of a weird new era of web performance where the metrics of web performance have shifted to user-centric measurements, but people are implementing tricky strategies to game those numbers with methods that, if anything, slightly harm user experience.

Direct Link to ArticlePermalink

The post Tricking CWV appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

How to describe element’s natural sizing behavior

Css Tricks - Fri, 03/26/2021 - 11:19am

PPK:

When introducing width and height I explain that by default width takes as much horizontal space as it can, while height takes as little vertical space as possible. This leads to a discussion of these two opposed models that I excerpt below.

My question is: which names do I give to these models?

The three options:

  • inside-out and outside-in
  • context-based and content-based
  • extrinsic and intrinsic size

There is more context in the post.

I definitely don’t like inside-out and outside-in — they make my head spin. I think I’m gonna vote for extrinsic and intrinsic size. I hear those terms thrown around a lot more lately and the fact that they match the specs is something I like. At the same time, I do feel like context-based and content-based are maybe a smidge more clear, but since they are already abstracted and made up, might as well go with the abstracted and made up term that already has legs.

Direct Link to ArticlePermalink

The post How to describe element’s natural sizing behavior appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Want to Write a Hover Effect With Inline CSS? Use CSS Variables.

Css Tricks - Fri, 03/26/2021 - 4:42am

The other day I was working on a blog where each post has a custom color attached to it for a little dose of personality. The author gets to pick that color in the CMS when they’re writing the post. Just a super-light layer of art direction.

To make that color show up on the front end, I wrote the value right into an inline style attribute on the <article> element. My templates happened to be in Liquid, but this would look similar in other templating languages:

{% for post in posts %} <article style="background: {{post.custom_color}}"> <h1>{{post.title}}</h1> {{content}} </article> {% endfor %}

No problem there. But then I thought, “Wouldn’t it be nice if the custom color only showed up when when hovering over the article card?” But you can’t write hover styles in a style attribute, right?

My first idea was to leave the style attribute in place and write CSS like this:

article { background: lightgray !important; } article:hover { /* Doesn't work! */ background: inherit; }

I can override the inline style by using !important, but there’s no way to undo that on hover.

Eventually, I decided I could use a style attribute to get the color value from the CMS, but instead of applying it right away, store it as a CSS variable:

<article style="--custom_color: {{post.custom_color}}"> <h1>{{post.title}}</h1> {{content}} </article>

Then, that variable can be used to define the hover style in regular CSS:

article { background: lightgray; } article:hover { /* Works! */ background: var(--custom_color); }

Now that the color value is saved as a CSS variable, there are all kinds of other things we can do with it. For instance, we could make all links in the post appear in the custom color:

article a { color: var(--custom_color); }

And because the variable is scoped to the <article> element, it won’t affect anything else on the page. We can even display multiple posts on the same page where each one renders in its own custom color.

CodePen Embed Fallback

Browser support for CSS variables is pretty deep, with the exception of Internet Explorer. Anyway, just a neat little trick that might come in handy if you find yourself working with light art direction in a CMS, as well as a reminder of just how awesome CSS variables can be.

The post Want to Write a Hover Effect With Inline CSS? Use CSS Variables. appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Syndicate content
©2003 - Present Akamai Design & Development.