Tag: Platform

Embrace the Platform

So what is the one thing that people can do is to make their website better? To answer that, let’s take a step back in time …

The year is 1998, and the web is on the rise. In an attempt to give a high-level overview of the architecture of the WWW, Tim Berners-Lee — yes, that Tim Berners-Lee — publishes a paper called “Web Architecture from 50,000 feet”. The report covers lots of things: content negotiation, the semantic web, HTML, CSS, and cool URIs (which don’t change), among others.

In the article, Berners-Lee also notes a few design principles very early on. One of those principles is the “Rule of Least Power.”

The Rule of Least Power goes like this:

When designing computer systems, one is often faced with a choice between using a more or less powerful language for publishing information, for expressing constraints, or for solving some problem. […] The “Rule of Least Power” suggests choosing the least powerful language suitable for a given purpose.

We have three main languages available on the web for the front end:

HTML

Semantically describes the content

CSS

Controls the presentation and layout

JavaScript

Adds interactivity and behavior

The Rule of Least Power suggests trying and doing as much as possible using HTML before resorting to CSS. Once CSS is no longer sufficient, grab for JavaScript — but only if you really have to.

As Derek Featherstone nicely put it:

In the web front-end stack — HTML, CSS, JS, and ARIA — if you can solve a problem with a simpler solution lower in the stack, you should. It’s less fragile, more foolproof, and just works.

💡 Hold up: This doesn’t mean you should set font sizes and colors via markup — a thing we used to do in the “olden” days of the web. Case in point: one of the rules covered in Berners-Lee’s piece is the separation of form and content.

The broken web

It has been almost 25 years since Berners-Lee published that article. Yet, somehow, the message he sent didn’t get through, and many developers — but not all — are unaware of it. Take this situation Drew Devault encountered not so long ago:

My browser has been perfectly competent at submitting HTML forms for the past 28 years, but for some stupid reason some developer decided to reimplement the form in JavaScript, and now I can’t pay my electricity bill without opening up the dev tools.

Sadly, this is no isolated case but rather a familiar phenomenon. All too often, I see websites and libraries that try to be clever or attempt to reinvent the wheel — primarily by throwing a bunch of JavaScript at it. In their attempt to do so, they achieve the exact opposite of what they were aiming at: those websites become less functional, less accessible, or — even worse — don’t work at all under certain conditions.

While a form might be a familiar example, there are more situations where applying the Rule of Least Power gives better results:

In all these examples, we can move some functionality from an upper into a lower layer. Berners-Lee would be proud of us.

Resilience

By choosing a technology lower in the web stack, closer to the core of the web platform, we also gain the benefit of built-in resilience against failures.

JavaScript is terrible at failing. One script that fails to load or gets mangled in the process, or one wrong argument to a function, and your whole app may no longer work. If an error message like “Cannot read property x of undefined” sounds familiar to you, you know what I’m talking about.

CSS, on the other hand, is very good at failing. Even if you have a syntax error in one of your style sheets, the rest of your CSS will still work. Same with HTML. These are forgiving languages.

If you doubt why you should use the Rule of Least Power, Jeremy Keith brings us the answer in his article “Evaluating Technology”:

We tend to ask “How well does it work?”, but what you should really be asking is “How well does it fail?”

Jeremy Keith

We can do better

A high-profile website that could benefit from the Rule of Least Power is the Nike website. When you visit their site with JavaScript disabled, you don’t get to see any images, nor do you get to order any shoes.

The same Nike product page with JavaScript (left) and without (right).

This over-reliance on JavaScript is not necessary as all those broken features can be built with technologies lower in the frontend stack:

  • Why not immediately include <img> elements to show the shoe photos instead of dynamically injecting them via JavaScript?
  • Why not use a <form> with a <select> (to choose your size) and a submit <button> to order the shoes, rather than managing the entire state and submission through JavaScript?

☝️ If you’re wondering why someone would ever browse the web with JavaScript disabled: it’s often not their choice but an external factor that’s interfering. See “Everyone has JavaScript, right?” for a good explanation on the topic.

Even worse offenders in this category are high-profile sites like Instagram and Twitter. Without JavaScript these websites don’t work at all. They either give you a warning, or simply remain blank. Since when is JavaScript required to show text and images on the web?

Progressive enhancement

It doesn’t have to be as bad as this isolated Nike example. Sometimes it’s smaller components that refuse to work when JavaScript fails. Take a tabbed interface as an example. Even though you can find many JavaScript libraries that provide this functionality, the kicker is that you don’t need JavaScript for that, as HTML, CSS, and ARIA themselves are already capable of getting you very far.

Once you have those base layers in place, use JavaScript to improve the experience further. Think of JavaScript as an enhancement instead of a requirement.

The same goes for certain CSS features that may or may not be available. Provide basic styling, and when a feature is available — detectable using @supports — enhance the result you already had.

This approach is known as progressive enhancement: You add functionality as more features become available, making the result better as far as the experience goes, but not so much that the feature cannot work without those extra flourishes.

And for browsers that don’t yet support a particular new feature, you can try and find a polyfill that provides that functionality to the browsers.

The web catches up

Since the web’s early days, we’ve seen the web platform gain many new features over time. New HTML elements were defined, JavaScript (the language) has matured, and CSS has gotten many powerful new features for building layouts, animating elements, etc.

Things that were impossible years ago and that could only be done by relying on external technologies, like Flash, are now built into the browser itself.

A classic example is the features jQuery introduced. Over ten years ago, jQuery was the very first thing to drop into a project. Today, that’s no longer the case, as the web platform has caught up and now has document.querySelectorAll(), Element.classList, etc. built-in — all features inspired upon features jQuery gave us. You could say that jQuery was a polyfill before polyfills even were called polyfills.

While jQuery might be a familiar example, there are many other situations where the web has caught up:

The central theme here is that these features no longer rely on a polyfill or an external library but have shifted closer to the core of the web stack. The web catches up.

While some of these new APIs can be pretty abstract, there are libraries out there that you can plug into your code. An example is Redaxios, which uses fetch under the hood while also exposing a developer-friendly, Axios-compatible API. It wouldn’t surprise me if these convenience methods eventually trickle down into the web platform.

In closing

What Berners-Lee wrote almost 25 years ago stands the test of time. It’s up to us, developers, to honor that message. By embracing what the web platform gives us — instead of trying to fight against it — we can build better websites.

Keep it simple. Apply the Rule of Least Power. Build with progressive enhancement in mind.

HTML, CSS, and JavaScript — in that order.

CSS-Tricks

,

Using the platform

While I’m a front-end developer at heart, I’ve rarely had the luxury of focusing on it full time. I’ve been dipping in and out of JavaScript, never fully caught up, always trying to navigate the ecosystem all over again each time a project came up. And framework fatigue is real!

So, instead of finally getting into Rollup to replace an ancient Browserify build on one of our codebases (which could also really use that upgrade from Polymer to LitElement…), I decided to go “stackless”.

Elise Hein

I’m certainly not dogmatic about it, but I think if you can pull of a project with literally zero build process. It feels good while working on it and feels very good when you come back to it months/years later. Plus you just pick up and go.

Imports, yo — they go a long way.

Native support for modularity is the most important step towards a build-free codebase. If I had access to only one ES6 feature for the rest of my life, I’m confident that modules would take me most of the way there when it comes to well-structured native JavaScript.

That last sentence in the post is a stinger. I’d say we’re not far off.

Direct Link to ArticlePermalink


The post Using the platform appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

,
[Top]

Hashnode: A Blogging Platform for Developers

Hashnode is a free developer blogging platform. Say you’ve just finished an ambitious project and want to write about 10 important lessons you’ve learned as a developer during it. You should definitely blog it—I love that kind of blog post, myself. Making a jump into the technical debt of operating your own blog isn’t a small choice, but it’s important to own your own content. With Hashnode, the decision gets a lot easier. You can blog under a site you entirely own, and at the same time, reap the benefits of hosted software tailor-made for developer blogging and be part of a social center around developer writing.

Here are some things, technologically, I see and like:

  • Write in Markdown. I’m not sure I’ve ever met a developer who didn’t prefer writing in
    Markdown.
  • Its not an “own your content” as in theoretically you could export content. Your content is in your GitHub repo. You wanna migrate it later? Go for it.
  • Your site, whether at your own custom domain or at a free subdomain, is hosted, CDN-backed, and SSL secured, while being customizable to your own style.
  • Developer specific features are there, like syntax highlighting for your code.
  • You get to be part of on-site community as well as a behind-the-scenes Discord community.
  • Your blog is highly optimized for performance, accessibility, and SEO. You’ll be hitting 100’s on Lighthouse reports, which is no small feat. Why not find out more info here about the advantages of having good SEO!

Your future biggest fans are there waiting for you ;).

Example of my personalized Hashnode newsletter with the best stuff from my feed.

The team over there isn’t oblivious to the other hosted blogging platforms out there. We’ve all seen programming blog posts on Medium, right? They tend to be one-offs in my experience. Hashnode is a Medium-alternative for developers. Medium just doesn’t cater particularly well to the developer audience. Plus you never know when your content will end up being behind a random paywall, a mega turn-off to fellow developers just trying to learn something. No ads or paywalls on Hashnode, ever.

The smart move, I’d say, is buying a domain name to represent yourself right away. I think that’s a super valuable stepping stone in all developer journeys. Then hook it up to Hashnode. Then wherever you do from that day forward, you are building domain equity there. You’re never going to regret that. That domain strength belongs entirely to you forever. Not to mention Medium wants $ 50/year to map a domain and DEV doesn’t let you do it at all.

But building your own site can be a lonely experience at first. The internet is a big place and you’ll be a small fish and first. By starting off at Hashnode, it’s like having a cheat code for being a much bigger fish right on day one.

DEV is out there too being a developer writing hub, but they don’t allow you to host your own site and build your own domain equity, as Hashnode does, or customize it to your liking as deeply.

Hashnode is built by developers, for developers, for real. Blogging for devs! The team there is very interested and receptive to your feature requests—so hit them up!

One more twist here that you might just love.

Hashnode Sponsors is a new way your fans can help monetize your blog directly, and Hashnode doesn’t take a cut of it at all.


The post Hashnode: A Blogging Platform for Developers appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,
[Top]

App Platform on Digital Ocean

This is new stuff from DO.

App Platform is a hosting product, no surprise there, but it has some features that are Jamstack-inspired in the best possible way, and an additional set of unique and powerful features. Let’s start with some basics:

  • Static sites can be hosted on the free tier
  • Automatic HTTPS
  • Global CDN (Cloudflare is in front, so you’re DDoS safe)
  • Deploy from Git

That’s the stuff that developers like me are loving these days. Take some of the hardest, toil-laden, no-fun aspects of web development and entirely do them for me.

And now the drumroll:

  • This isn’t just for static sites: it’s for PHP, Node, Python, Ruby, Go, Docker Containers, etc.
  • You don’t have to configure and update things, these are boxes ready-to-go for those technologies.
  • You can scale to whatever you need.
  • You don’t pay by the team seat. Unlimited team members. You pay by usage like bandwidth and build time.

Use that link to get $ 100 in credit over 60 days.

It extremely easy to deploy a static site

You snag it right from GitHub (or GitLab, or Docker Hub), which is great right away, and off you go.

Then we get our first little hint of something compelling right away:

But let’s say we don’t need that immediately, we can go with a free plan and get this out.

The site will build and you can see logs:

And lookie that my static site is LIVE!

Say my site needs to run an actual build process? That, and lots more configuration come in the form of an “App Spec”. This is where I would include those build commands, change Git information, deployment zones, and loads more.

About that database…

Wasn’t that interesting to see the setup steps for this static site suggest adding a database? So many sites need some kind of data store, and it’s often left up to developers to go find some kind of cloud-accessible data storage that will work well with their app. With Digital Ocean App Platform, it can live right alongside your static app.

It’s called a component.

As you can see, it can be, but doesn’t have to be a Database. It could be another type of server! Here I could pop a PostgreSQL DB on there for just $ 7/month.

If what you need to add is an internal or external service, it will let you add that via another Git repo that you hook up. Oh my what a modern system you now have. A front end and a back end each individually deployable directly via Git itself.

This is for server-side apps as well.

This feels big to me! I get that same kinda easy DX feeling I get with static sites, but with, say, a Python or Ruby on Rails app. Free deployment! Server boxes I don’t have to configure and manage myself!

Seems like a pretty happy-path hosting environment for lots of stuff.

Use that link to get $ 100 in credit over 60 days.


The post App Platform on Digital Ocean appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, ,
[Top]

Scaling Organizations Should Consider Building a Website Backed by a CRM Platform

To make some terminology clear here:

  • CMS = Content Management System
  • CRM = Customer Relationship Management

Both are essentially database-backed systems for managing data. HubSpot is both, and much more. Where a CMS might be very focused on content and the metadata around making content useful, a CRM is focused on leads and making communicating with current and potential customers easier.

They can be brothers-in-arms. We’ll get to that.

Say a CRM is set up for people. You run a Lexus dealership. There is a quote form on the website. People fill it out and enter the CRM. That lead can go to your sales team for taking care of that customer.

But a CRM could be based on other things. Say instead of people it’s based on real estate listings. Each main entry is a property, with essentially metadata like photos, address, square footage, # of bedrooms/baths, etc. Leads can be associated with properties.

That would be a nice CRM setup for a real estate agency, but the data that is in that CRM might be awfully nice for literally building a website around those property listings. Why not tap into that CRM data as literal data to build website pages from?

That’s what I mean by a CRM and CMS being brothers-in-arms. Use them both! That’s why HubSpot can be an ideal home for websites like this.

To keep that tornado of synergy going, HubSpot can also help with marketing, customer service, and integrations. So there is a lot of power packed into one platform.

And with that power, also a lot of comfort and flexibility.

  • You’re still developing locally.
  • You’re still using Git.
  • You can use whatever framework or site-building tools you want.
  • You’ve got a CLI to control things.
  • There is a VS Code Extension for super useful auto-complete of your data.
  • There is a staging environment.

And the feature just keep coming. HubSpot really has a robust set of tools to make sure you can do what you need to do.

As developer-rich as this all is, it doesn’t mean that it’s developer-only. There are loads of tools for working with the website you build that require no coding at all. Dashboard for content management, data wrangling, style control, and even literal drag-and-drop page builders.

It’s all part of a very learnable system.

Themestemplatesmodules, and fields are the objects you’ll work with most in HubSpot CMS as a developer. Using these different objects effectively lets you give content creators the freedom to work and iterate on websites independently while staying inside style and layout guardrails you set.


The post Scaling Organizations Should Consider Building a Website Backed by a CRM Platform appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , , , ,
[Top]

Platform News: Using :focus-visible, BBC’s New Typeface, Declarative Shadow DOMs, A11Y and Placeholders

There’s a whole lot of accessibility in this week’s news, from the nuances of using :focus-visible and input placeholders, to accessible typefaces and a Safari bug with :display: contents. Plus, a snippet for a bare-bones web component that supports style encapsulation.

Now may be a good time to start using :focus-visible

The CSS :focus-visible pseudo-class replaces :focus as the new way to create custom focus indicators for keyboard users. Chrome recently switched from :focus to :focus-visible in the user agent stylesheet and, as a result of that change, the default focus ring is no longer shown when the user clicks or taps a button.

When switching from :focus to :focus-visible, consider backwards compatibility. Your keyboard focus indicators should be clearly visible in all browsers, not just the ones that support :focus-visible. If you only style :focus-visible, non-supporting browsers will show the default focus ring which, depending on your design, “may not be sufficiently clear or visible at all.”

button {   background: white; }  button:focus-visible {   outline: none;   background: #ffdd00; /* gold */ }

A good way to start using :focus-visible today is to define the focus styles in a :focus rule and then immediately undo these same styles in a :focus:not(:focus-visible) rule. This is admittedly not the most elegant and intuitive pattern, but it works well in all browsers:

  • Browsers that don’t support :focus-visible use the focus styles defined in the :focus rule and ignore the second style rule completely (because :focus-visible is unknown to them).
  • In browsers that do support :focus-visible, the second style rule reverts the focus styles defined in the :focus rule if the :focus-visible state isn’t active as well. In other words, the focus styles defined in the :focus rule are only in effect when :focus-visible is also active.
button:focus {   outline: none;   background: #ffdd00; /* gold */ }  button:focus:not(:focus-visible) {   background: white; /* undo gold */ }

The BBC created a more accessible typeface

The BBC created their own custom typeface called Reith (named after the BBC’s founder Sir John Reith). Their goal was to create a font that supports multiple languages and is easier to read, especially on small devices. The font was tested with mixed-ability user groups (dyslexia and vision impairment) and across different screen sizes.

We [the BBC] were using Helvetica or Arial. We also had Gill Sans as the corporate typeface. These typefaces were designed a hundred years ago for the printed page [and] don’t perform well on today’s modern digital screens.

Reith Sans can bee seen in use on BBC Sport

Note: If you’d like to inspect Reith Sans and Reith Serif in Wakamai Fondue, you can quickly access the URLs of the WOFF2 files in the “All fonts on page” section of the Fonts pane in Firefox’s DOM inspector on BBC’s website.

display: contents is still not accessible in Safari

The CSS display: contents value has been supported in browsers since 2018. An element with this value “does not generate any boxes” and is effectively replaced by its children. This is especially useful in flex and grid layouts, where the contents value can be used to “promote” more deeply nested elements to flex/grid items while retaining a semantic document structure.

Source: Manuel Rego Casasnovas

Unfortunately, this feature originally shipped with an implementation bug that removed the element from the browser’s accessibility tree. For example, applying display: contents to a <ul> element resulted in that element no longer mentioned by screen readers. Since then, this bug has been fixed in Firefox and Chrome (in the latest version).

View on CodePen

In Chrome and Firefox, the screen reader informs the user that the “Main, navigation” contains a “list, 2 items.” In Safari, the latter part is missing because the <ul> and <li> elements are not present in the accessibility tree. Until Apple fixes this bug in Safari, be careful when using the contents value on semantic elements and test in screen readers to confirm that your pages are accessible in Safari as well.

Set opacity when overriding the color of placeholder text

Accessibility experts recommend avoiding placeholders if possible because they can be confused for pre-populated text and disappear when the user starts entering a value. However, many websites (including Wikipedia and GOV.UK) use placeholders in simple web forms that contain only a single input field, such as a search field.

The subscription form for the CSS-Tricks newsletter uses a placeholder in the email field

Placeholders can be styled via the widely supported ::placeholder pseudo-element. If your design calls for a custom color for placeholder text, make sure to specify both color and opacity. The latter is needed for Firefox, which applies opacity: 0.54 to ::placeholder by default. If you don’t override this value, your placeholder text may have insufficient contrast in Firefox.

.search-field::placeholder {   color: #727272;   opacity: 1; /* needed for Firefox */ }
The placeholder text on eBay’s website is lighter in Firefox and doesn’t meet the minimum contrast requirement of 4.5:1

Declarative shadow DOM could help popularize style encapsulation

One of the key features of shadow DOM is style encapsulation, wherein the outer page’s style rules don’t match elements inside the shadow tree, and vice versa. In order to use this feature, you need to attach a shadow DOM tree to an element (usually a custom element, like <my-element>) and copy the element’s template (usually from a <template> element in the DOM) to the element’s newly created shadow DOM.

These steps can only be performed in JavaScript. If you’re only interested in style encapsulation and don’t need any dynamic functionality for your element, here is the minimum amount of JavaScript required to create a custom element with a shadow DOM:

customElements.define(   "my-element",   class extends HTMLElement {     constructor() {       super();        // find <template id="my-template"> in the DOM       let template = document.getElementById("my-template");        // make a copy of the template contents…       let content = template.content.cloneNode(true);        // …and inject it into <my-element>’s shadow DOM       this.attachShadow({ mode: "open" }).appendChild(content);     }   } );

For an example of style encapsulation, see Miriam Suzanne’s <media-object> element on CodePen. The scoped styles are located in the <template> element in the HTML pane. Notice how this CSS code can use simple selectors, such as article, that only match elements inside <media-object>’s shadow DOM.

JavaScript may soon no longer be required to create this type of style encapsulation in modern browsers. Earlier this week, Chrome became the first browser to ship Google’s Declarative Shadow DOM proposal. If it becomes a standard, this feature will also make it possible to use Shadow DOM in combination with server-side rendering.


The post Platform News: Using :focus-visible, BBC’s New Typeface, Declarative Shadow DOMs, A11Y and Placeholders appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , , , , ,
[Top]

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

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:

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.

Three sets of round yellow buttons, comparing how Chrome, Firefox, and Safari handle outlines.

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.

Side by side comparison of the Performance tab in Chrome DevTools.
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.

Screenshot of the crossword game with an open screen reader dialog announcing what is on the screen.
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.

Two CSS rulesets, one as Option A and the other as Option B, both showing how variables are inherited and resolved between elements.

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.

CSS-Tricks

, , , , , , ,
[Top]

Platform News: Prefers Contrast, MathML, :is(), and CSS Background Initial Values

In this week’s round-up, prefers-contrast lands in Safari, MathML gets some attention, :is() is actually quite forgiving, more ADA-related lawsuits, inconsistent initial values for CSS Backgrounds properties can lead to unwanted — but sorta neat — patterns.

The prefers-contrast: more media query is supported in Safari Preview

After prefers-reduced-motion in 2017, prefers-color-scheme in 2019, and forced-colors in 2020, a fourth user preference media feature is making its way to browsers. The CSS prefers-contrast: more media query is now supported in the preview version of Safari. This feature will allow websites to honor a user’s preference for increased contrast.

Screenshot of the iPhone 12 landing page on Apple's website. A big red arrow points out light grey text on the page.
Apple could use this new media query to increase the contrast of gray text on its website
.pricing-info {   color: #86868b; /* contrast ratio 3.5:1 */ }  @media (prefers-contrast: more) {   .pricing-info {     color: #535283; /* contrast ratio 7:1 */   } }

Making math a first-class citizen on the web

One of the earliest specifications developed by the W3C in the mid-to-late ’90s was a markup language for displaying mathematical notations on the web called MathML. This language is currently supported in Firefox and Safari. Chrome’s implementation was removed in 2013 because of “concerns involving security, performance, and low usage on the Internet.”

If you’re using Chrome or Edge, enable “Experimental Web Platform features” on the about:flags page to view the demo.

There is a renewed effort to properly integrate MathML into the web platform and bring it to all browsers in an interoperable way. Igalia has been developing a MathML implementation for Chromium since 2019. The new MathML Core Level 1 specification is a fundamental subset of MathML 3 (2014) that is “most suited for browser implementation.” If approved by the W3C, a new Math Working Group will work on improving the accessibility and searchability of MathML.

The mission of the Math Working Group is to promote the inclusion of mathematics on the Web so that it is a first-class citizen of the web that displays well, is accessible, and is searchable.

CSS :is() upgrades selector lists to become forgiving

The new CSS :is() and :where() pseudo-classes are now supported in Chrome, Safari, and Firefox. In addition to their standard use cases (reducing repetition and keeping specificity low), these pseudo-classes can also be used to make selector lists “forgiving.”

For legacy reasons, the general behavior of a selector list is that if any selector in the list fails to parse […] the entire selector list becomes invalid. This can make it hard to write CSS that uses new selectors and still works correctly in older user agents.

In other words, “if any part of a selector is invalid, it invalidates the whole selector.” However, wrapping the selector list in :is() makes it forgiving: Unsupported selectors are simply ignored, but the remaining selectors will still match.

Unfortunately, pseudo-elements do not work inside :is() (although that may change in the future), so it is currently not possible to turn two vendor-prefixed pseudo-elements into a forgiving selector list to avoid repeating styles.

/* One unsupported selector invalidates the entire list */ ::-webkit-slider-runnable-track, ::-moz-range-track {   background: red; }  /* Pseudo-elements do not work inside :is() */ :is(::-webkit-slider-runnable-track, ::-moz-range-track) {   background: red; }  /* Thus, the styles must unfortunately be repeated */ ::-webkit-slider-runnable-track {   background: red; } ::-moz-range-track {   background: red; }

Dell and Kraft Heinz sued over inaccessible websites

More and more American businesses are facing lawsuits over accessibility issues on their websites. Most recently, the tech corporation Dell was sued by a visually impaired person who was unable to navigate Dell’s website and online store using the JAWS and VoiceOver screen readers.

The Defendant fails to communicate information about its products and services effectively because screen reader auxiliary aids cannot access important content on the Digital Platform. […] The Digital Platform uses visual cues to convey content and other information. Unfortunately, screen readers cannot interpret these cues and communicate the information they represent to individuals with visual disabilities.

Earlier this year, Kraft Heinz Foods Company was sued for failing to comply with the Web Content Accessibility Guidelines on one of the company’s websites. The complaint alleges that the website did not declare a language (lang attribute) and provide accessible labels for its image links, among other things.

In the United States, the Americans with Disabilities Act (ADA) applies to websites, which means that people can sue retailers if their websites are not accessible. According to the CEO of Deque Systems (the makers of axe), the recent increasing trend of web-based ADA lawsuits can be attributed to a lack of a single overarching regulation that would provide specific compliance requirements.

background-clip and background-origin have different initial values

By default, a CSS background is painted within the element’s border box (background-clip: border-box) but positioned relative to the element’s padding box (background-origin: padding-box). This inconsistency can result in unexpected patterns if the element’s border is semi-transparent or dotted/dashed.

A pink and triple rectangle with rounded edges. The colors overlap in a pattern.
.box {   /* semi-transparent border */   border: 20px solid rgba(255, 255, 255, 0.25);    /* background gradient */   background: conic-gradient(     from 45deg at bottom left,     deeppink,     rebeccapurple   ); }

Because of the different initial values, the background gradient in the above image is repeated as a tiled image on all sides under the semi-transparent border. In this case, positioning the background relative to the border box (background-origin: border-box) makes more sense.


The post Platform News: Prefers Contrast, MathML, :is(), and CSS Background Initial Values appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , ,
[Top]

Platform News: Defaulting to Logical CSS, Fugu APIs, Custom Media Queries, and WordPress vs. Italics

Looks like 2021 is the time to start using CSS Logical Properties! Plus, Chrome recently shipped a few APIs that have raised eyebrows, SVG allows us to disable its aspect ratio, WordPress focuses on the accessibility of its typography, and there’s still no update (or progress) on the development of CSS custom media queries.

Let’s jump right into the news…

Logical CSS could soon become the new default

Six years after Mozilla shipped the first bits of CSS Logical Properties in Firefox, this feature is now on a path to full browser support in 2021. The categories of logical properties and values listed in the table below are already supported in Firefox, Chrome, and the latest Safari Preview.

CSS property or value The logical equivalent
margin-top margin-block-start
text-align: right text-align: end
bottom inset-block-end
border-left border-inline-start
(n/a) margin-inline

Logical CSS also introduces a few useful shorthands for tasks that in the past required multiple declarations. For example, margin-inline sets the margin-left and margin-right properties, while inset sets the top, right, bottom and left properties.

/* BEFORE */ main {   margin-left: auto;   margin-right: auto; }  /* AFTER */ main {   margin-inline: auto; }

A website can add support for an RTL (right-to-left) layout by replacing all instances of left and right with their logical counterparts in the site’s CSS code. Switching to logical CSS makes sense for all websites because the user may translate the site to a language that is written right-to-left using a machine translation service. The biggest languages with RTL scripts are Arabic (310 million native speakers), Persian (70 million), and Urdu (70 million).

/* Switch to RTL when Google translates the page to an RTL language */ .translated-rtl {   direction: rtl; }

David Bushell’s personal website now uses logical CSS and relies on Google’s translated-rtl class to toggle the site’s inline base direction. Try translating David’s website to an RTL language in Chrome and compare the RTL layout with the site’s default LTR layout.

Chrome ships three controversial Fugu APIs

Last week Chrome shipped three web APIs for “advanced hardware interactions”: the WebHID and Web Serial APIs on desktop, and Web NFC on Android. All three APIs are part of Google’s capabilities project, also known as Project Fugu, and were developed in W3C community groups (though they’re not web standards).

  • The WebHID API allows web apps to connect to old and uncommon human interface devices that don’t have a compatible device driver for the operating system (e.g., Nintendo’s Wii Remote).
  • The Web Serial API allows web apps to communicate (“byte by byte”) with peripheral devices, such as microcontrollers (e.g., the Arduino DHT11 temperature/humidity sensor) and 3D printers, through an emulated serial connection.
  • Web NFC allows web apps to wirelessly read from and write to NFC tags at short distances (less than 10 cm).

Apple and Mozilla, the developers of the other two major browser engines, are currently opposed to these APIs. Apple has decided to “not yet implement due to fingerprinting, security, and other concerns.” Mozilla’s concerns are summarized on the Mozilla Specification Positions page.

Source: webapicontroversy.com

Stretching SVG with preserveAspectRatio=none

By default, an SVG scales to fit the <svg> element’s content box, while maintaining the aspect ratio defined by the viewBox attribute. In some cases, the author may want to stretch the SVG so that it completely fills the content box on both axes. This can be achieved by setting the preserveAspectRatio attribute to none on the <svg> element.

View demo

Distorting SVG in this manner may seem counterintuitive, but disabling aspect ratio via the preserveAspectRatio=none value can make sense for simple, decorative SVG graphics on a responsive web page:

This value can be useful when you are using a path for a border or to add a little effect on a section (like a diagonal [line]), and you want the path to fill the space.

WordPress tones down the use of italics

An italic font can be used to highlight important words (e.g., the <em> element), titles of creative works (<cite>), technical terms, foreign phrases (<i>), and more. Italics are helpful when used discreetly in this manner, but long sections of italic text are considered an accessibility issue and should be avoided.

Italicized text can be difficult to read for some people with dyslexia or related forms of reading disorders.

Putting the entire help text in italics is not recommended

WordPress 5.7, which was released earlier this week, removed italics on descriptions, help text, labels, error details text, and other places in the WordPress admin to “improve accessibility and readability.”

In related news, WordPress 5.7 also dropped custom web fonts, opting for system fonts instead.

Still no progress on CSS custom media queries

The CSS Media Queries Level 5 module specifies a @custom-media rule for defining custom media queries. This proposed feature was originally added to the CSS spec almost seven years ago (in June 2014) and has since then not been further developed nor received any interest from browser vendors.

@custom-media --narrow-window (max-width: 30em);  @media (--narrow-window) {   /* narrow window styles */ }

A media query used in multiple places can instead be assigned to a custom media query, which can be used everywhere, and editing the media query requires touching only one line of code.

Custom media queries may not ship in browsers for quite some time, but websites can start using this feature today via the official PostCSS plugin (or PostCSS Preset Env) to reduce code repetition and make media queries more readable.

On a related note, there is also the idea of author-defined environment variables, which (unlike custom properties) could be used in media queries, but this potential feature has not yet been fully fleshed out in the CSS spec.

@media (max-width: env(--narrow-window)) {   /* narrow window styles */ }

The post Platform News: Defaulting to Logical CSS, Fugu APIs, Custom Media Queries, and WordPress vs. Italics appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , , , , ,
[Top]

Weekly Platform News: Focus Rings, Donut Scope, Ditching em Units, and Global Privacy Control

In this week’s news, Chrome tackles focus rings, we learn how to get “donut” scope, Global Privacy Control gets big-name adoption, it’s time to ditch pixels in media queries, and a snippet that prevents annoying form validation styling.

Chrome will stop displaying focus rings when clicking buttons

Chrome, Edge, and other Chromium-based browsers display a focus indicator (a.k.a. focus ring) when the user clicks or taps a (styled) button. For comparison, Safari and Firefox don’t display a focus indicator when a button is clicked or tapped, but do only when the button is focused via the keyboard.

The focus ring will stay on the button until the user clicks somewhere else on the page.

Some developers find this behavior annoying and are using various workarounds to prevent the focus ring from appearing when a button is clicked or tapped. For example, the popular what-input library continuously tracks the user’s input method (mouse, keyboard or touch), allowing the page to suppress focus rings specifically for mouse clicks.

[data-whatintent="mouse"] :focus {   outline: none; }

A more recent workaround was enabled by the addition of the CSS :focus-visible pseudo-class to Chromium a few months ago. In the current version of Chrome, clicking or tapping a button invokes the button’s :focus state but not its :focus-visible state. that way, the page can use a suitable selector to suppress focus rings for clicks and taps without affecting keyboard users.

:focus:not(:focus-visible) {   outline: none; }

Fortunately, these workarounds will soon become unnecessary. Chromium’s user agent stylesheet recently switched from :focus to :focus-visible, and as a result of this change, button clicks and taps no longer invoke focus rings. The new behavior will first ship in Chrome 90 next month.

The enhanced CSS :not() selector enables “donut scope”

I recently wrote about the A:not(B *) selector pattern that allows authors to select all A elements that are not descendants of a B element. This pattern can be expanded to A B:not(C *) to create a “donut scope.”

For example, the selector article p:not(blockquote *) matches all <p> elements that are descendants of an <article> element but not descendants of a <blockquote> element. In other words, it selects all paragraphs in an article except the ones that are in a block quotation.

The donut shape that gives this scope its name

The New York Times now honors Global Privacy Control

Announced last October, Global Privacy Control (GPC) is a new privacy signal for the web that is designed to be legally enforceable. Essentially, it’s an HTTP Sec-GPC: 1 request header that tells websites that the user does not want their personal data to be shared or sold.

The DuckDuckGo Privacy Essentials extension enables GPC by default in the browser

The New York Times has become the first major publisher to honor GPC. A number of other publishers, including The Washington Post and Automattic (WordPress.com), have committed to honoring it “this coming quarter.”

From NYT’s privacy page:

Does The Times support the Global Privacy Control (GPC)?

Yes. When we detect a GPC signal from a reader’s browser where GDPR, CCPA or a similar privacy law applies, we stop sharing the reader’s personal data online with other companies (except with our service providers).

The case for em-based media queries

Some browsers allow the user to increase the default font size in the browser’s settings. Unfortunately, this user preference has no effect on websites that set their font sizes in pixels (e.g., font-size: 20px). In part for this reason, some websites (including CSS-Tricks) instead use font-relative units, such as em and rem, which do respond to the user’s font size preference.

Ideally, a website that uses font-relative units for font-size should also use em values in media queries (e.g., min-width: 80em instead of min-width: 1280px). Otherwise, the site’s responsive layout may not always work as expected.

For example, CSS-Tricks switches from a two-column to a one-column layout on narrow viewports to prevent the article’s lines from becoming too short. However, if the user increases the default font size in the browser to 24px, the text on the page will become larger (as it should) but the page layout will not change, resulting in extremely short lines at certain viewport widths.

If you’d like to try out em-based media queries on your website, there is a PostCSS plugin that automatically converts min-width, max-width, min-height, and max-height media queries from px to em.

(via Nick Gard)

A new push to bring CSS :user-invalid to browsers

In 2017, Peter-Paul Koch published a series of three articles about native form validation on the web. Part 1 points out the problems with the widely supported CSS :invalid pseudo-class:

  • The validity of <input> elements is re-evaluated on every key stroke, so a form field can become :invalid while the user is still typing the value.
  • If a form field is required (<input required>), it will become :invalid immediately on page load.

Both of these behaviors are potentially confusing (and annoying), so websites cannot rely solely on the :invalid selector to indicate that a value entered by the user is not valid. However, there is the option to combine :invalid with :not(:focus) and even :not(:placeholder-shown) to ensure that the page’s “invalid” styles do not apply to the <input> until the user has finished entering the value and moved focus to another element.

The CSS Selectors module defines a :user-invalid pseudo-class that avoids the problems of :invalid by only matching an <input> “after the user has significantly interacted with it.”

Firefox already supports this functionality via the :-moz-ui-invalid pseudo-class (see it in action). Mozilla now intends to un-prefix this pseudo-class and ship it under the standard :user-invalid name. There are still no signals from other browser vendors, but the Chromium and WebKit bugs for this feature have been filed.


The post Weekly Platform News: Focus Rings, Donut Scope, Ditching em Units, and Global Privacy Control appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , , , , , ,
[Top]