Front End Web Development

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.

Building a Full-Stack Geo-Distributed Serverless App with Macrometa, GatsbyJS, & GitHub Pages

Css Tricks - Thu, 03/25/2021 - 4:15am

In this article, we walk through building out a full-stack real-time and completely serverless application that allows you to create polls! All of the app’s static bits (HTML, CSS, JS, & Media) will be hosted and globally distributed via the GitHub Pages CDN (Content Delivery Network). All of the data and dynamic requests for data (i.e., the back end) will be globally distributed and stateful via the Macrometa GDN (Global Data Network).

Macrometa is a geo-distributed stateful serverless platform designed from the ground up to be lightning-fast no matter where the client is located, optimized for both reads and writes, and elastically scalable. We will use it as a database for data collection and maintaining state and stream to subscribe to database updates for real-time action.

We will be using Gatsby to manage our app and deploy it to Github Pages. Let’s do this!

Intro

This demo uses the Macrometa c8db-source-plugin to get some of the data as markdown and then transform it to HTML to display directly in the browser and the Macrometa JSC8 SKD to keep an open socket for real-time fun and manage working with Macrometa’s API.

Getting started
  1. Node.js and npm must be installed on your machine.
  2. After you have that done, install the Gatsby-CLI >> npm install -g gatsby-cli
  3. If you don’t have one already go ahead and signup for a free Macrometa developer account.
  4. Once you’re logged in to Macrometa create a document collection called markdownContent. Then create a single document with title and content fields in markdown format. This creates your data model the app will be using for its static content.

Here’s an example of what the markdownContent collection should look like:

{ "title": "## Real-Time Polling Application", "content": "Full-Stack Geo-Distributed Serverless App Built with GatsbyJS and Macrometa!" }

content and title keys in the document are in the markdown format. Once they go through gatsby-source-c8db, data in title is converted to <h2></h2>, and content to <p></p>.

  1. Now create a second document collection called polls. This is where the poll data will be stored.

In the polls collection each poll will be stored as a separate document. A sample document is mentioned below:

{ "pollName": "What is your spirit animal?", "polls": [ { "editing": false, "id": "975e41", "text": "dog", "votes": 2 }, { "editing": false, "id": "b8aa60", "text": "cat", "votes": 1 }, { "editing": false, "id": "b8aa42", "text": "unicorn", "votes": 10 } ] } Setting up auth

Your Macrometa login details, along with the collection to be used and markdown transformations, has to be provided in the application’s gatsby-config.js like below:

{ resolve: "gatsby-source-c8db", options: { config: "https://gdn.paas.macrometa.io", auth: { email: "<my-email>", password: "process.env.MM_PW" }, geoFabric: "_system", collection: 'markdownContent', map: { markdownContent: { title: "text/markdown", content: "text/markdown" } } } }

Under password you will notice that it says process.env.MM_PW, instead of putting your password there, we are going to create some .env files and make sure that those files are listed in our .gitignore file, so we don’t accidentally push our Macrometa password back to Github. In your root directory create .env.development and .env.production files.

You will only have one thing in each of those files: MM_PW='<your-password-here>'

Running the app locally

We have the frontend code already done, so you can fork the repo, set up your Macrometa account as described above, add your password as described above, and then deploy. Go ahead and do that and then I’ll walk you through how the app is set up so you can check out the code.

In the terminal of your choice:

  1. Fork this repo and clone your fork onto your local machine
  2. Run npm install
  3. Once that’s done run npm run develop to start the local server. This will start local development server on http://localhost:<some_port> and the GraphQL server at http://localhost:<some_port>/___graphql
How to deploy app (UI) on GitHub Pages

Once you have the app running as expected in your local environment simply run npm run deploy!

Gatsby will automatically generate the static code for the site, create a branch called gh-pages, and deploy it to Github.

Now you can access your site at <your-github-username>.github.io/tutorial-jamstack-pollingapp

If your app isn‘t showing up there for some reason go check out your repo’s settings and make sure Github Pages is enabled and configured to run on your gh-pages branch.

Walking through the code

First, we made a file that loaded the Macrometa JSC8 Driver, made sure we opened up a socket to Macrometa, and then defined the various API calls we will be using in the app. Next, we made the config available to the whole app.

After that we wrote the functions that handle various front-end events. Here’s the code for handling a vote submission:

onVote = async (onSubmitVote, getPollData, establishLiveConnection) => { const { title } = this.state; const { selection } = this.state; this.setState({ loading: true }, () => { onSubmitVote(selection) .then(async () => { const pollData = await getPollData(); this.setState({ loading: false, hasVoted: true, options: Object.values(pollData) }, () => { // open socket connections for live updates const onmessage = msg => { const { payload } = JSON.parse(msg); const decoded = JSON.parse(atob(payload)); this.setState({ options: decoded[title] }); } establishLiveConnection(onmessage); }); }) .catch(err => console.log(err)) }); } You can check out a live example of the app here

You can create your own poll. To allow multiple people to vote on the same topic just share the vote URL with them.

Try Macrometa

The post Building a Full-Stack Geo-Distributed Serverless App with Macrometa, GatsbyJS, & GitHub Pages appeared first on CSS-Tricks.

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

CSS terminology question

QuirksBlog - Thu, 03/25/2021 - 1:32am

I need to figure out how to call a pair of fundamental CSS concepts in my upcoming book and would like to hear which option you think is best — or least confusing.

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?

  1. The excerpt uses the names inside-out and outside-in — the ones I decided to use initially. However, a Twitter thread revealed two other good options:
  2. context-based and content-based
  3. extrinsic and intrinsic size, which I think are the terms used in the specifications. I'm afraid they may seem daunting to novices — you need to know what extrinsic and intrinsic mean.

Results: Content- and context-base 130 votes (62%); intrinsic and extrinsic 53 votes (25%); inside-out and outside-in 26 votes (12%).

So the terms will be content-based and context-based. Duly noted.

Excerpt from the Flow chapter

Here follows an excerpt from my current draft.

[end of previous section]

We’ll get back to setting widths and heights later [in the book]. For now it’s enough to note that their default behavior is quite different: width takes as much horizontal space as it can, while height takes as little vertical space as it can. Understanding this difference is key to understanding the browsers’ default layout.

Inside-out and outside-in

An important purpose of any layout module is figuring out what dimensions blocks should take. Why does a block have the width and height that it has? How do browsers determine that?

There are two models for determining block sizes: the outside-in model and the inside-out model. Width works outside-in, while height works inside-out. What does that mean?

In the outside-in model the block looks at the context outside itself to figure out which dimensions it should have. For instance, the default width of a paragraph is determined by the width of its container. If that container width changes, for instance because the user resizes the browser window, the width of the paragraphs changes in reaction to these factors outside themselves. Grid layout is another example of outside-in: it gives a central definition of the columns and rows that all blocks obey. If that definition changes, the blocks’ dimensions also change, regardless of their content.

In the inside-out model the block looks at its content to figure out which dimensions it should take. For instance, the default height of a paragraph is determined by the amount of text it contains. If a script adds more text, the paragraph’s height grows in reaction to these factors inside it. Flexbox layout is another example of inside-out: all individual items in a flexbox look at their contents first to determine their width. If the content of an item changes, the item’s width also changes, regardless of its neighbors.

If a script adds text to a paragraph its width stays the same. Width does not concern itself with what happens inside the paragraph; only with external factors.

Inside-out is more complex than outside-in because indirectly it may also react to outside factors. When the user makes the browser window narrower the width of the paragraphs decreases, which means less text fits on one line, which means the text needs more lines, which means the height of the paragraphs increases. Height is still inside-out, though: the reason the height changes is that the contents of the paragraphs need more space.The fact that they need more space because of the outside-in changes to the width is irrelevant to the height calculation.

As a general rule, when you create a layout you set outside-in dimensions such as width and grid fairly strictly, while you generally leave inside-out dimensions such as height and the width of flex items alone. Like any general rule this one has plenty of exceptions, and we'll encounter some of them in later chapters. Still, if you're unfamilier with CSS layout I advise you to stick to setting outside-in sizes, and allow the browser to set inside-out sizes for itself. That will make your life a lot easier.

Excerpt ends.

Maps Scroll Wheel Fix

Css Tricks - Tue, 03/23/2021 - 1:51pm

This blog post by Steve Fenton came across my feeds the other day. I’d never heard of HERE maps before, but apparently they are embeddable somehow, like Google Maps. The problem is that you zoom and and out of HERE maps with the scrollwheel. So imagine you’re scrolling down a page, your cursor (or finger) ends up on the HERE map, and now you can’t continue scrolling down the page because that scrolling event is captured by the map and turns into map zooming.

Steve’s solution: put a “coverer” <div> over the map when a scroll event starts on the window, and remove it after a short delay (when scrolling “stops”). That solution resonates with me, as not only have I coded solutions like that in the past for embedded maps, we have a solution like that in place on CodePen today. On CodePen, you can resize the “preview” window, which is an <iframe> of the code you write. If you drag too swiftly, your mouse cursor (or touch event) might trigger movement off of the draggable element, possible onto the <iframe> itself. If that happens, the <iframe> will swallow the event, and the resizing you are trying to do stops working correctly. To prevent this, we put a “covered” <div> over top the <iframe> while you are dragging, and remove it when you stop dragging.

Thinking of maps though, it reminds me Brad Frost’s Adaptive Maps idea documented back in 2012. The idea is that embedding a map on a small screen mobile device just isn’t a good idea. Space is cramped, they can slow down page load, and, like Steve experienced nearly a decade later, they can mess with users scrolling through the page. Brads solution is to serve an image of a map (which can still be API-driven) conditionally for small screens with a “View Map” link that takes them to a full-screen map experience, probably within the map native app itself. Large screens can still have the interactive map, although, I might argue that having the image-that-links-to-map-service might be a smart pattern for any browser with less technical debt.

The post Maps Scroll Wheel Fix appeared first on CSS-Tricks.

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

Imagining native skip links

Css Tricks - Tue, 03/23/2021 - 11:32am

I love it when standards evolve from something that a bunch of developers are already doing, and making it easier and foolproof. Kitty Giraudel is onto that here with skip links, something that every website should probably have, and that has a whole checklist of things that we can and do screw up:

  • It should be the first thing to tab into.
  • It should be hidden carefully so it remains focusable.
  • When focused, it should become visible.
  • Its content should start with “Skip” to be easily recognisable.
  • It should lead to the main content of the page.

Doing this natively could solve all those problems and more (like displaying in the correct language for that user). Nice little project for someone to mock up as a browser extension, I’d say.

Reminds me of the idea of extending the Web Share API into native HTML. It’s just a good idea.

Direct Link to ArticlePermalink

The post Imagining native skip links appeared first on CSS-Tricks.

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

Syndicate content
©2003 - Present Akamai Design & Development.