Tag: support

Adding Fluid Typography Support to WordPress Block Themes

Fluid typography is a fancy way of “describing font properties, such as size or line height, that scale fluidly according to the size of the viewport”. It’s also known by other names, like responsive typography, flexible type, fluid type, viewport sized typography, fluid typography, and even responsive display text.

Here is an example of fluid typography that you can play live (courtesy of MDN documentation). CSS-Tricks has covered fluid typography extensively as well. But the point here is not to introduce you to fluid typography, but how to use it. More specifically, I want to show you how to implement fluid typography in WordPress 6.1 which recently introduced a fluid type feature directly in the WordPress Block Editor.

Open up your style.css file, slap in a style rule with fancy clamp()-ing on the font-size property, and good to go, right? Sure, that’ll give you fluid text, but to get Block Editor controls that make it possible to apply fluid type anywhere on your WordPress site? That requires a different approach in these block-ified days.

Fluid typography support in Gutenberg

Some WordPress theme developers have been using the clamp() function to define a fluid font-size, in their WordPress themes, even in newer “block” themes such as Twenty Twenty-Two, Twenty Twenty-Three, and others.

But the Gutenberg plugin — the one that contains experimental development for WordPress Block and Site Editor features — introduced support for fluid typography starting in version 13.8. That opened the door for implementing at a theme level so that fluid type can be applied to specific elements and blocks directly in the Block Editor. CSS-Tricks was even given a shout-out in the Pull Request that merged the feature.

That work became part of WordPress Core in WordPress 6.1. Rich Tabor, one of the earlier advocates of fluid typography in the Block Editor says:

[Fluid typography] is also a part of making WordPress more powerful, while not more complicated (which we all know is quite the challenge). […] Fluid typography just works. Actually, I think it works great.

This Make WordPress post highlights the approach taken to support the feature at the block level so that a fluid font size is applied to blocks dynamically by default. There are some benefits to this, of course:

  • It provides a way for theme authors to activate fluid typography without worrying about implementing it in code.
  • It applies fluid typography to specific typographical entities, such as elements or blocks in a maintainable and reusable way.
  • It allows flexibility in terms of font size units (e.g. px, rem, em, and %).

Now that this new feature is available in the WordPress Block Editor by default, theme authors can apply uniform fluid typography without writing additional code.

Blocks that support typography and spacing settings

Gutenberg 14.1 released on September 16, 2022, and introduced typographic settings on a bunch of blocks. That means the text settings for those blocks were set in CSS before and had to be changed in CSS as well. But those blocks now provide font and spacing controls in the Block Editor interface.

Illustrated list of WordPress blocks that received font and spacing controls in the Gutenberg plugin. There are 31 total blocks.

That work is currently slated to be added to WordPress 6.1, as detailed in this Make WordPress blog post. And with it is an expanded number of blocks that with typography support.

Illustrated list of 60 WordPress blocks gaining typography and font size support in WordPress 6.1.
WordPress blocks that will support typography settings in the upcoming WordPress 6.1 release.

Declaring fluid type in a WordPress block theme

So, how do we put this new fluid typography to use in WordPress? The answer is in theme.json, a new-ish file specific to block themes that contains a bunch of theme configurations in key:value pairs.

Let’s look at a rule for a large font in theme.json where contentSize: 768px and we’re working with a widesize: 1600px layout. This is how we can specify a CSS font-size using the clamp() function:

"settings": {   "appearanceTools": true,   "layout": {     "contentSize": "768px",     "wideSize": "1600px"   },   "typography": {     "fontSizes": [        {         "name": "Large",         "size": "clamp(2.25rem, 6vw, 3rem)",         "slug": "large"       }     ]   } }

As of WordPress 6.1, only rem, em and px units are supported.

That’s great and works, but with the new fluid type feature we would actually use a different approach. First, we opt into fluid typography on settings.typography, which has a new fluid property:

"settings": {   "typography": {     "fluid": true   } }

Then we specify our settings.fontSizes like before, but with a new fluidSize property where we can set the min and max size values for our fluid type range.

"settings": {   "appearanceTools": true,   "layout": {     "contentSize": "768px",     "wideSize": "1600px"   },   "typography": {     "fontSizes": [        {         "size": "2.25rem",         "fluidSize": {           "min": "2.25rem",           "max": "3rem"         },         "slug": "large",         "name": "Large"       }     ]   } }

That’s really it. We just added fluid type to a font size called “Large” with a range that starts at 2.25rem and scales up to 3rem. Now, we can apply the “Large” font to any block with font settings.

How does this works under the hood? Rich Tabor offers a nice explanation, as does this Pull Request in GitHub. In short, WordPress converts the theme.json properties into the following CSS rule:

.has-large-font-size {   font-size: clamp(36px, calc(2.25rem + ((1vw - 7.68px) * 1.4423)), 48px); }

…which is applied to the element, say a Paragraph Block:

<p class="has-large-font-size">...</p>

Initially, I found it hard to understand and wrap around in my mind the concept of the CSS clamp() function without also learning about the min(), max(), and calc() functions. This calculator tool helped me quite a bit, especially for determining which values to use in my own theme projects.

For demonstration purposes, let’s use the calculator to define our font-size range so that the size is 36px at a 768px viewport width and 48px at a 1600px viewport width.

Entering values into the online calculator for fluid typography.

The calculator automatically generates the following CSS:

/* 36px @ 768px increasing to 48px @ 1600px */ font-size: clamp(36px, calc(2.25rem + ((1vw - 7.68px) * 1.4423)), 48px);

The calculator provide options to select input units as px, rem, and em. If we select rem unit, the calculator generates the following clamp() value:

/* 2.25rem @ 48rem increasing to 3rem @ 100rem */ font-size: clamp(2.25rem, calc(2.25rem + ((1vw - 0.48rem) * 1.4423)), 3rem);

So, those minimum and maximum values correspond to the the fluidSize.min and fluidSize.max values in theme.json. The min value is applied at viewports that are 768px wide and below. Then the font-size scales up as the viewport width grows. If the viewport is wider than 1600px, the max is applied and the font-size is capped there.

Examples

There are detailed testing instructions in the merged Pull Request that introduced the feature. There are even more testing instructions from Justin Tadlock’s pre-prelease post on Make WordPress.

Example 1: Setting a new fluid font setting

Let’s start with Justin’s set of instructions. I used in a modified version of the default Twenty Twenty-Three theme that is currently under development.

First, let’s make sure we’re running the Gutenberg plugin (13.8 and up) or WordPress 6.1, then opt into fluid type on the settings.typography.fluid property in the theme.json file:

{   "version": 2,   "settings": {     "appearanceTools": true,     "layout": {       "contentSize": "768px",       "wideSize": "1600px"     },     "typography": {       "fluid": true     }   } }

Now, let’s drop the settings.typography.fontSizes examples in there:

{   "version": 2,   "settings": {     "appearanceTools": true,     "layout": {       "contentSize": "768px",       "wideSize": "1600px"     },     "typography": {       "fluid": true       "fontSizes": [         {           "name": "Normal",           "size": "1.125rem",           "fluid": {             "min": "1rem",             "max": "1.5rem"           },           "slug": "normal"         }       ]     }   } }

If everything is working correctly, we can now head into the WordPress Block Editor and apply the “Normal” font setting to our block:

The WordPress Block Editor interface showing a paragraph block and the fluid typography settings for it.

Nice! And if we save and inspect that element on the front end, this is the markup:

Inspecting the WordPress Paragraph block in DevTools.

Very good. Now let’s make sure the CSS is actually there:

DevTools showing the font-size custom property for the WordPress Paragraph block's fluid typography.

Good, good. Let’s expose that CSS custom property to see if it’s really clampin’ things:

Revealing the custom property value in DevTools, showing a CSS clamp function.

Looks like everything is working just as we want it! Let’s look at another example…

Example 2: Excluding a font setting from fluid type

This time, let’s follow the instructions from the merged Pull Request with a nod to this example by Carolina Nymark that shows how we can disable fluid type on a specific font setting.

I used the empty theme as advised in the instructions and opened up the theme.json file for testing. First, we opt into fluid type exactly as we did before:

{   "version": 2,   "settings": {     "appearanceTools": true,     "layout": {       "contentSize": "768px",       "wideSize": "1000px"     },     "typography": {       "fluid": true     }   } }

This time, we’re working with smaller wideSize value of 1000px instead of 1600px. This should allow us to see fluid type working in an exact range.

OK, on to defining some custom font sizes under settings.typography.fontSizes:

{   "version": 2,   "settings": {     "typography": {       "fluid": true,       "fontSizes": [         {           "size": ".875rem",           "fluid": {             "min": "0.875rem",             "max": "1rem"         },           "slug": "small",           "name": "Small"         },         {           "size": "1rem",           "fluid": {             "min": "1rem",             "max": "1.5rem"           },           "slug": "normal",           "name": "Normal"         },         {           "size": "1.5rem",           "fluid": {             "min": "1.5rem",             "max": "2rem"           },           "slug": "large",           "name": "Large"         },         {           "size": "2.25rem",           "fluid": false,           "slug": "x-large",           "name": "Extra large"         }       ]     }   } }

Notice that we’ve applied the fluid type feature only on the “Normal”, “Medium”, and “Large” font settings. “Extra Large” is the odd one out where the fluid object is set to false.

the WordPress Block Editor interface with four Paragraph blocks, each at a different font size setting.

What WordPress does from here — via the Gutenberg style engine — is apply the properties we set into CSS clamp() functions for each font size setting that has opted into fluid type and a single size value for the Extra Large setting:

--wp--preset--font-size--small: clamp(0.875rem, 0.875rem + ((1vw - 0.48rem) * 0.24), 1rem); --wp--preset--font-size--medium: clamp(1rem, 1rem + ((1vw - 0.48rem) * 0.962), 1.5rem); --wp--preset--font-size--large: clamp(1.5rem, 1.5rem + ((1vw - 0.48rem) * 0.962), 2rem); --wp--preset--font-size--x-large: 2.25rem;

Let’s check the markup on the front end:

Inspecting the WordPress Paragraph blocks in DevTools.

Good start! Let’s confirm that the .has-x-large-font-size class is excluded from fluid type:

Showing the font-size custom property for the Extra Large font setting in DevTools.

If we expose the --wp--preset--font-size--x-large variable, we’ll see it’s set to 2.25rem.

Revealing the Extra Large font size custom property value, showing 2.25rem.

That’s exactly what we want!

Block themes that support fluid typography

Many WordPress themes already make use of the clamp() function for fluid type in both block and classic themes. A good example of fluid typography use is the recently released Twenty Twenty-Three default theme.

I’ve reviewed all the block themes from WordPress Block Theme directory, examining theme.json file of each theme and to see just how many block themes currently support fluid typography — not the new feature since it’s still in the Gutenberg plugin as of this writing — using the CSS clamp() function. Of the 146 themes I reviewed, the majority of them used a clamp() function to define spacing. A little more than half of them used clamp() to define font sizes. The Alara theme is the only one to use clamp() for defining the layout container sizes.

Understandably, only a few recently released themes contain the new fluid typography feature. But here are the ones I found that define it in theme.json:

And if you read my previous post here on CSS-Tricks, the TT2 Gopher Blocks theme I used for the demo has also been updated to support the fluid typography feature.

Selected reactions to the WordPress fluid typography features

Having fluid typography in WordPress at the settings level is super exciting! I thought I’d share some thoughts from folks in the WordPress developer community who have commented on it.

Matias Ventura, the lead architect of the Gutenberg project:

Rich Tabor:

As one of the bigger efforts towards making publishing beautifully rich pages in WordPress, fluid typography is a pretty big experience win for both the folks building with WordPress — and those consuming the content.

Automattic developer Ramon Dodd commented in the Pull Request:

Contrast that idea with font sizes that respond to specific viewport sizes, such as those defined by media queries, but do nothing in between those sizes. theme.json already allows authors to insert their own fluid font size values. This won’t change, but this PR offers it to folks who don’t want to worry about the implementation details.

Nick Croft, author of GenesisWP:

Brian Garner, designer and principal developer advocate at WPEngine:

A few developers think some features should be an opt-in. Jason Crist of Automattic says:

I love the power of fluid typography, however I also don’t believe that it should just be enabled by default. It’s usage (and the details of it) are important design decisions that should be made carefully.

You can also find a bunch more comments in the official testing instructions for the feature.

Wrapping up

The fluid typography feature in WordPress is still in active development at the time of this writing. So, right now, theme authors should proceed to use it, but with caution and expect some possible changes before it is officially released. Justin cautions theme authors using this feature and suggests to keep eye on the following two GitHub issues:

There is also still lots of ongoing work on typography and other design-related WordPress tools. If you’re interested, watch this typography tracking GitHub ticket and design tools related GitHub issues.

Resources

I used the following articles when researching fluid type and how WordPress is implementing it as a feature.

Tutorials and opinions

CSS-Tricks


Adding Fluid Typography Support to WordPress Block Themes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

CSS-Tricks

, , , , , ,

Detecting Media Query Support in CSS and JavaScript

You can’t just do @media (prefers-reduced-data: no-preference) alone because, as Kilian Valkhof says:

[…] that would be false if either there was no support (since the browser wouldn’t understand the media query) or if it was supported but the user wanted to preserve data.

Usually @supports is the tool for this in CSS, but that doesn’t work with @media queries. Turns out there is a solution though:

@media not all and (prefers-reduced-data), (prefers-reduced-data) {   /* ... */ }

This is a somewhat complex logic puzzle involving media query syntax and how browsers evaluate these things. It’s nice you can ultimately handle a no-support fallback situation in one expression.

Direct Link to ArticlePermalink


The post Detecting Media Query Support in CSS and JavaScript appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

Safari 14.1 Adds Support for Flexbox Gaps

Yay, it’s here! Safari 14.1 reportedly adds support for the gap property in flexbox layouts. We’ve had grid-gap support for some time, but true to its name, it’s limited to grid layouts. Now we can use gap in either type of layout:

.container {   display: flex;   flex-flow: row wrap;   gap: 1.5rem; }

Apple’s been rather quiet about the update. I didn’t even hear about it until Eric Meyer brought it up in an email, and he only heard about it when Jen Simmons tweeted it out.

I checked the WebKit CSS Feature Status and, sure enough, it’s supported. It just wasn’t called out in the release notes. Nothing is posted to Safari’s release notes archive just yet, so maybe we’ll hear about it officially there at some point. For now, it seems that Maximiliano Firtman‘s overview of iOS 14.5 is the deepest look at what’s new.

And how timely is it that Eric recently covered how to use the gap property, not only in grid and flexbox layouts, but multi-column as well.


The post Safari 14.1 Adds Support for Flexbox Gaps appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , ,
[Top]

:focus-visible Support Comes to Firefox

Look at that! The :focus-visible pseudo-selector is now supported in Firefox, as of version 85 which shipped yesterday. I had to rush over to the MDN Docs just to confirm, and yep, the :focus-visible page has been updated to reflect the news.

What’s so cool about :focus-visible? It’s all about the blue focus ring that displays around elements that are in focus. It’s sort of a happy medium between loving the outline for accessibility purposes (gotta know what element is selected when tabbing on a keyboard) but not-really-loving how it looks (gotta have everything follow brand).

The strategy has largely been an all-or-nothing choice between using a custom outline when any element is in :focus (great, but that means for both keyboard tabbing and mouse clicks) or ditching the outline altogether (not great, like ever). :focus-visible accomplishes the same thing as :focus, but uses a browser’s knowledge of user inputs (or heuristics) to determine whether the focus is coming from a keyboard or a mouse.

(Are a browser’s heuristics perfect at determining the input? That depends. Things get murky once we start factoring in things like touch interactions.)

That means, we get to remove the default focus ring (yay!) for the right types of interactions (double yay!) and display our own custom styles while we’re at it (triple yay!). Allow me to pluck Andy Adams’ fine example straight from our almanac. Note that :focus-visible cannot remove the focus ring like :focus can, so the two are used together:

.next-image-button:focus {   outline: none; }  .next-image-button:focus-visible {   outline: 3px solid blanchedalmond; /* That'll show 'em */ }

Chrome implemented :focus-visible back in 2018. Firefox had it’s own prefixed version, :-moz-focusring, prior to this implementation. Safari? Go vote for the feature!


The post :focus-visible Support Comes to Firefox appeared first on CSS-Tricks.

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

CSS-Tricks

, , ,
[Top]

Weekly Platform News: The :not() pseudo-class, Video Media Queries, clip-path: path() Support

Hey, we’re back with weekly updates about the browser landscape from Šime Vidas.

In this week’s update, the CSS :not pseudo class can accept complex selectors, how to disable smooth scrolling when using “Find on page…” in Chrome, Safari’s support for there media attribute on <video> elements, and the long-awaited debut of the path() function for the CSS clip-path property.

Let’s jump into the news…

The enhanced :not() pseudo-class enables new kinds of powerful selectors

After a years-long wait, the enhanced :not() pseudo-class has finally shipped in Chrome and Firefox, and is now supported in all major browser engines. This new version of :not() accepts complex selectors and even entire selector lists.

For example, you can now select all <p> elements that are not contained within an <article> element.

/* select all <p>s that are descendants of <article> */ article p { }  /* NEW! */ /* select all <p>s that are not descendants of <article> */ p:not(article *) { }

In another example, you may want to select the first list item that does not have the hidden attribute (or any other attribute, for that matter). The best selector for this task would be :nth-child(1 of :not([hidden])), but the of notation is still only supported in Safari. Luckily, this unsupported selector can now be re-written using only the enhanced :not() pseudo-class.

/* select all non-hidden elements that are not preceded by a non-hidden sibling (i.e., select the first non-hidden child */ :not([hidden]):not(:not([hidden]) ~ :not([hidden])) { }

The HTTP Refresh header can be an accessibility issue

The HTTP Refresh header (and equivalent HTML <meta> tag) is a very old and widely supported non-standard feature that instructs the browser to automatically and periodically reload the page after a given amount of time.

<!-- refresh page after 60 seconds --> <meta http-equiv="refresh" content="60">

According to Google’s data, the <meta http-equiv="refresh"> tag is used by a whopping 2.8% of page loads in Chrome (down from 4% a year ago). All these websites risk failing several success criteria of the Web Content Accessibility Guidelines (WCAG):

If the time interval is too short, and there is no way to turn auto-refresh off, people who are blind will not have enough time to make their screen readers read the page before the page refreshes unexpectedly and causes the screen reader to begin reading at the top.

However, WCAG does allow using the <meta http-equiv="refresh"> tag specifically with the value 0 to perform a client-side redirect in the case that the author does not control the server and hence cannot perform a proper HTTP redirect.

(via Stefan Judis)

How to disable smooth scrolling for the “Find on page…” feature in Chrome

CSS scroll-behavior: smooth is supported in Chrome and Firefox. When this declaration is set on the <html> element, the browser scrolls the page “in a smooth fashion.” This applies to navigations, the standard scrolling APIs (e.g., window.scrollTo({ top: 0 })), and scroll snapping operations (CSS Scroll Snap).

Unfortunately, Chrome erroneously keeps smooth scrolling enabled even when the user performs a text search on the page (“Find on page…” feature). Some people find this annoying. Until that is fixed, you can use Christian Schaefer’s clever CSS workaround that effectively disables smooth scrolling for the “Find on page…” feature only.

@keyframes smoothscroll1 {   from,   to {     scroll-behavior: smooth;   } }  @keyframes smoothscroll2 {   from,   to {     scroll-behavior: smooth;   } }  html {   animation: smoothscroll1 1s; }  html:focus-within {   animation-name: smoothscroll2;   scroll-behavior: smooth; }

In the following demo, notice how clicking the links scrolls the page smoothly while searching for the words “top” and “bottom” scrolls the page instantly.

Safari still supports the media attribute on video sources

With the HTML <video> element, it is possible to declare multiple video sources of different MIME types and encodings. This allows websites to use more modern and efficient video formats in supporting browsers, while providing a fallback for other browsers.

<video>   <source src="/flower.webm" type="video/webm">   <source src="/flower.mp4" type="video/mp4"> </video>

In the past, browsers also supported the media attribute on video sources. For example, a web page could load a higher-resolution video if the user’s viewport exceeded a certain size.

<video>   <source media="(min-width: 1200px)" src="/large.mp4" type="video/mp4">   <source src="/small.mp4" type="video/mp4"> </video>

The above syntax is in fact still supported in Safari today, but it was removed from other browsers around 2014 because it was not considered a good feature:

It is not appropriate for choosing between low resolution and high resolution because the environment can change (e.g., the user might fullscreen the video after it has begun loading and want high resolution). Also, bandwidth is not available in media queries, but even if it was, the user agent is in a better position to determine what is appropriate than the author.

Scott Jehl (Filament Group) argues that the removal of this feature was a mistake and that websites should be able to deliver responsive video sources using <video> alone.

For every video we embed in HTML, we’re stuck with the choice of serving source files that are potentially too large or small for many users’ devices … or resorting to more complicated server-side or scripted or third-party solutions to deliver a correct size.

Scott has written a proposal for the reintroduction of media in video <source> elements and is welcoming feedback.

The CSS clip-path: path() function ships in Chrome

It wasn’t mentioned in the latest “New in Chrome 88” article, but Chrome just shipped the path() function for the CSS clip-path property, which means that this feature is now supported in all three major browser engines (Safari, Firefox, and Chrome).

The path() function is defined in the CSS Shapes module, and it accepts an SVG path string. Chris calls this the ultimate syntax for the clip-path property because it can clip an element with “literally any shape.” For example, here’s a photo clipped with a heart shape:


The post Weekly Platform News: The :not() pseudo-class, Video Media Queries, clip-path: path() Support appeared first on CSS-Tricks.

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

CSS-Tricks

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

WordPress.com Business Plan (Business-Class WordPress Hosting + Support from WordPress Experts)

WordPress.com is where you go to use WordPress that is completely hosted for you. You don’t have to worry about anything but building your site. There is a free plan to get started with, and paid plans that offer more features. The Business plan is particularly interesting, and my guess is that most people don’t fully understand everything that it unlocks for you, so let’s dig into that.

You get straight up SFTP access to your site.

Here’s me using Transmit to pop right into one of my sites over SFTP.

What this means is that you can do local WordPress development like you normally would, then use real deployment tools to kick your work out to production (which is your WordPress.com site). That’s what I do with Buddy. (Here a screencast demonstrating the workflow.)

That means real control.

I can upload and use whatever plugins I want. I can upload and use whatever themes I want. The database too — I get literal direct MySQL access.

I can even manage what PHP version the site uses. That’s not something I’d normally even need to do, but that’s just how much access there is.

A big jump in storage.

200 GB. You’ll probably never get anywhere near that limit, unless you are uploading video, and if you are, now you’ve got the space to do it.

Backups you’ll probably actually use.

You don’t have to worry about anything nasty happening on WordPress.com, like your server being hacked and losing all your data or anything. So in that sense, WordPress.com is handling your backups for you. But with the Business plan, you’ll see a backup log right in your dashboard:

That’s a backup of your theme, data, assets… everything. You can download it anytime you like.

The clutch feature? You can restore things to any point in time with the click of a button.

Powered by a global CDN

Not every site on WordPress.com is upgraded to the global CDN. Yours will be if it’s on the Business plan. That means speed, and speed is important for every reason, including SEO. And speaking of SEO tools, those are unlocked for you on the Business plan as well.

Some of the best themes unlock at the Premium/Business plan level.

You can buy them one-off, but you don’t have to if you’re on the Business plan because it opens the door for more playing around. This Aquene theme is pretty stylish with a high-end design:

It’s only $ 300/year.

(Or $ 33/month billed monthly.)

So it’s not ultra-budget hosting, but the price tag is a lot less if you consider all the things we covered here and how much they cost if you were to cobble something together yourself. And we didn’t even talk about support, which is baked right into the plan.

Hosting, backups, monitoring, performance, security, plugins, themes, and support — toss in a free year or domain registration, and that’s a lot of website for $ 300.

They have less expensive plans as well. But the Business plan is the level where serious control, speed, and security kick in.

Coupon code CSSTRICKS gets you 15% off the $ 300/year Business Plan. Valid until the end of February 2021.


The post WordPress.com Business Plan (Business-Class WordPress Hosting + Support from WordPress Experts) appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , , , , ,
[Top]

Overlaying Video With Transparency While Wrangling Cross-Browser Support

As websites are becoming more and more dynamic when it comes to design, there is sometimes a need to incorporate complex, animated elements. There are many ways to do that from CSS transitions to 3D rendering on canvas, and animated SVG. But it is often easier to use a <video> since they can be rather efficient and, with them, just about anything visual is possible.

But what if you a need transparent background on that video, so that it could overlay and appear to interact with other content on the page? It’s possible, but can be tricky, especially cross-browser. Let’s explore that.

Here’s an example

To see how transparent video overlays work, I’ve prepared an example that I hope feels both fun and relatable. The idea is to integrate video with interactive content underneath so that the content behind the video changes as the slider is advancing. It is a slider advertising dog food with a real video of a dog on the overlay and I’m sure that realistic, cute dog would improve the conversion rate!

You can follow along with this article to recreate this demo by yourself. Part of what you’ll need to create a video like this is an “image sequence” (a bunch of alpha-transparent images we’ll stitch together into a video). I’m providing the images I used for the example.

Exploring possibilities

To achieve this effect, I started with a search for any kind of solution that would allow me to insert animated content with transparent background on the page.

GIF

The first thing that came up was a GIF. Even though the GIF format was introduced over 30 years ago, it is still widely used. Unfortunately, it has its limitations. While it works perfectly for simple and small animated graphics, it is not that great for colorful, long video footage, it has limited color space, and will grow a lot in size for complex videos.

APNG

The next option I’ve looked at was APNG, which for some reason, is not as popular as GIF but is much better. (I didn’t even know it existed, did you?) APNG works similarly to animated GIF files while supporting 24-bit images and 8-bit transparency. It is also backward-compatible with regular PNG. If APNG is not supported, the first frame is displayed. It is supported by popular browsers, but no support in Internet Explorer 11 (yup, some people still have to support that). While it seemed like the way to go for a moment, I was not satisfied with its file size and performance.

Fun fact: Apple adopted the APNG format as their preferred format for animated stickers in iOS 10 iMessage apps.

Loop through PNGs

Next, a crude, but working, idea came to mind: use a bunch of PNGs and loop through them with JavaScript to imitate the video. But it requires using a lot of data transfer (each video frame would be a separate image) and resources to animate (you could drain a user’s battery quickly or make their computer fan go crazy).

I quickly abandoned that idea, but it turned out to be useful later. I’ll get back to that at the end of the article.

WebM with alpha transparency

As all the formats for <img> failed here, I started looking into videos. I found an article about alpha transparency in Chrome video published in 2013, which announces Google Chrome support for WebM with an alpha channel. It even shows an example and shares tips on how to use it. I went through the article and it immediately felt like the way to go. I was even more convinced after converting my image sequence to WebM because, while GIF was weighing in at 5.8 MB, WebM with transparency,using the same frame rate and full colors was only 540 KB! That’s more than 10 times smaller while offering better performance and quality. Awesome!

The joy did not last long though. As soon as I opened the website on my iOS Phone I realized that I should’ve started with checking the browser compatibility. Unfortunately, Safari (iOS and macOS) doesn’t support transparency in WebM. While my video was working perfectly on Chrome, Firefox and Edge, Safari greeted me with an ugly black background.

The search continues…

A good Solution

Thankfully, I found a video from WWDC 2019 announcing HEVC video with Alpha support for Safari starting in iOS 13 and macOS Catalina. It seemed to provide the same functionality as WebM but with support on Apple devices. So I decided to use the hybrid solution: HEVC for Safari and WebM for other browsers.

It seems like the perfect solution. But now we have two tasks:

  1. Create an HEVC with alpha-transparency
  2. Detect for Safari (and the version) to serve the correct format

Creating a transparent video

We will start with the easy part: creating a WebM file. If you want to create, convert, or even edit video files, FFmpeg is your friend. It is an extremely powerful open source multimedia framework, and if you have anything to do with multimedia files, I’d recommend starting there because it’s capable of so many things. I can say that FFmpeg has helped me reduce video file sizes over 10 times without any visible image quality degradation. But let’s get back to transparency.

In my experience, if you need to include animated elements into website layout, you get them as a set of video frames in PNG. Even while working on my example project, a tool that removes background from videos generated a set of images for me. So I will continue here assuming we’re building the video from a set of images (remember, you can download our set), but even if you’ve got a video file instead, the process will look similar (adjust FFmpeg options to your needs).

We are now ready to create a video. Using the command line, we’ll navigate to the folder that contains the PNG files and run the following command:

ffmpeg -framerate 25 -i unscreen-%3d.png -c:v libvpx-vp9 -pix_fmt yuva420p output.webm

You can adjust the arguments to fit your needs:

  • framerate: how much images will be used for 1s of the output video
  • -i unscreen-%3d.png: input file name and format. My files have numbers from 001 to 150 so i used %3d as a mask to select all files with three digits in the name.
  • -c:v: specifies the codec to use. I want the video to be encoded with VP9, which is supported by most web browsers.
  • -pix_fmt: specifies pixel format to be used. In our cas, it should support an alpha channel. You can see all supported formats if you run ffmpeg --pix_fmts.
  • output.webm: provides the desired output file name as a last argument

There are a lot more options available, but I won’t dive into details as it would take probably more than one article to go through them. Those provided in the example command work fine for our use case.

After the process is finished, we should see a new output.webm file, and if you open it in a supported browser, you’ll see a video. Easy, right?

Creating HEVC Alpha

Since we have a WebP file ready, it’s time to move to the second format we will be using: HEVC with alpha transparency. Unfortunately, at the time of writing, FFmpeg doesn’t support HEVC, so we have to use another tool. As far as I know, the only way to create HEVC with alpha is to use the Finder or Compressor on Mac. If you have a PC, you’ll probably have to ask someone with Mac to do it for you. The Compressor app is only provided with Final Cut Pro, so I won’t be using it, although it may be worth considering if you need custom settings.

Since macOS Catalina, the Finder has a built in Encode Media tool to convert videos. It is simple (and free), so it feeds our needs.

The Finder expects a video file as an input, so first, we have to convert the image sequence to ProRes 4444. This is an important step, as the Encode Media tool won’t accept just any video — it will fail unless you provide the format it accepts. It gave me a headache or two until I found out the correct encoding for the input file.

We can create input video using FFmpeg. As we did when creating WebM, we just have to run FFmpeg with the proper arguments:

ffmpeg -framerate 25 -i unscreen-%3d.png -c:v prores_ks -pix_fmt yuva444p10le -alpha_bits 16 -profile:v 4444 -f mov -vframes 150 output.mov

From this point on, a Mac is needed. But the process is simple and does not involve typing anything in terminal, so even if you ask a non-techy friend with a Mac to do it for you, I’m sure they can manage.

Having ProRes4444 video ready, you can navigate to the containing folder in Finder, right-click on it, and in the context menu, select Encode Selected Video Files.

A window will appear. Select the desired HEVC quality (there are two to choose from), and check the option to Preserve Transparency. Then click the “Continue” button.

After a moment you should see a new file, which is encoded in HEVC with alpha. It’s done! Opening this file in Safari confirm that the transparency works.

Last but not least, it’s time to use videos on the website!

Serving transparent videos for all browsers

We can use <video> element to serve videos. If the browser supports the given format in the src attribute, it will just work. But as I’ve mentioned, we need to serve HEVC for Safari and WebM for other browsers.

There is one more thing to take care of: some browsers support WebM or HEVC itself but without transparency. Those browsers will play the video but with a black background instead of an alpha channel. For example, Safari 12 will play HEVC without transparency. That’s unacceptable for us.

Normally, I’d use the <source /> element to provide the video along with multiple formats as fallbacks, and the browser would pick the one it supports. However, since we want to show HEVC only on specific Safari versions, we will have to set the video src attribute instead using JavaScript.

HEVC with transparency is supported in iOS 13 and Mac Safari 13, so let’s start by detecting those. The recommended way to adjust website features based on support is by detecting the existence of an API rather than looking at the User Agent, but I didn’t find any simple way to detect if the browser supports transparency in video format. Instead, I came up with my own solution. It’s not pretty, but it does the job.

function supportsHEVCAlpha() {   const navigator = window.navigator;   const ua = navigator.userAgent.toLowerCase()   const hasMediaCapabilities = !!(navigator.mediaCapabilities && navigator.mediaCapabilities.decodingInfo)   const isSafari = ((ua.indexOf('safari') != -1) && (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1)))   return isSafari && hasMediaCapabilities }

This targets Safari 13 and above by looking at navigator.mediaCapabilities, which is not supported in older versions, as well as looking that the browser is Safari at all. If the function returns true, then I’m good to go with HEVC alpha. For any other case, I’ll load WebM video.

Here’s an example of how this comes together in HTML:

<video id="player" loop muted autoplay playsinline></video>  <script> const player = document.getElementById('player'); player.src = supportsHEVCAlpha() ? 'output.mov' : 'output.webm'; </script>

If you’re curious about those loop muted autoplay playsinline arguments on video element, those are about replicating a GIF-like experience:

  • Without muted, the video will not play without user interaction.
  • With playsinline, on iOS, the video plays right where it is in the layout instead of opening up in fullscreen.
  • With loop, the video repeats over and over.
  • With autoplay, it will start playing the video automatically on page load (as long as we also have muted in place).

That’s it! We have a lightweight, performant and high-quality solution for transparent videos, that works on most modern browsers (at least the last two recent versions of Chrome, Firefox, Safari and Edge). We can add some basic HTML and CSS to integrate static content with it and make it a little bit more real-life, or just use the same idea that’s in my demo. That wasn’t too bad, was it?

Hey, but what about IE 11? My whole company is using it!

In general, I’d recommend limiting a feature like this to modern browsers and hiding the video in IE. The video is probably not a critical element of the website. Although, I used to work on a commercial project where IE 11 support was a must and I was forced to figure something out to show the transparent video there. In the end, I ended up cycling through PNG images with JavaScript. I reduced the amount of frames and switched between them using a timer. Sure, the performance was awful, but it worked. The video was quite important to the whole design so we intentionally decided to sacrifice performance on IE 11 to provide the full experience.

Summary

I hope that I’ve saved you some time researching the idea of alpha-transparent video and that now you’re be able to incorporate animated elements like this on your website. I bet you’ll need it someday!

Do you have a different idea of how to use transparent video? Or maybe some experience with that already? Let me know in the comments.


The post Overlaying Video With Transparency While Wrangling Cross-Browser Support appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , ,
[Top]

WooCommerce Payments, Now with Support for Subscriptions and Saved Cards

A little while back we shared the news that WooCommerce shipped a beta payments feature as part of its 4.0 release. It’s a free plugin with no monthly costs or setup fees. You only pay when you make a sale.

We’re actually using this right here at CSS-Tricks. In fact, Chris blogged it back in July. Back then, we were using the WooCommerce Payments beta so we could start selling memberships here on the site and do it while taking payments without anyone having to leave the site to complete the transaction with a third-party.

The big news now is that WooCommerce Payments now supports WooCommerce Subscriptions. This is game-changer. It means you can offer a recurring payment option on subscription-based products and have all of those payments integrated with WooCommerce Payments reporting and features.

WooCommerce Payments works alongside other payment methods! We’ve enabled PayPal for anyone who prefers paying that way.

Enter subscriptions

The thing that makes WooCommerce Subscriptions such a great extension is that it turns any WooCommerce product into a possible subscription. So, yes, even a t-shirt can generate recurring payments (a shirt is not a good example of a subscription product, but the point is that subscriptions can be tied to anything). Anything you want to renew after a period of time is fair game. That could be a publication subscription that renews annually, a record of the month club with a monthly subscription, or even a payment plan that allows customers to pay for large purchases in monthly installments.

No no, the poster is not a subscription… but you can buy it with a one-time payment!

Now that WooCommerce Payments supports WooCommerce Subscriptions, not only are recurring payments a thing, but it brings all of those transactions to your store’s dashboard, making it a cinch to track those payments, as well as your cash flow. Payment disputes can even be handled without ever having to leave WordPress.

Oh, and saved credit cards!

In addition to subscriptions, WooCommerce Payments also supports saved credit cards. So now, when someone purchases anything on your site — whether it’s a single product or a recurring subscription — they can choose to save their payment information with you for faster transactions on future purchases!

Heck yeah, checking out next time will be a breeze!

All the things, all on WordPress

WooCommerce has been great for a long time, but it’s these sorts of enhancements that make it not just a killer experience but makes powerful e-commerce capabilities open to big and small stores alike. Get started with WooCommerce and WooCommerce Payments — it’s totally free to pick up and try out.


The post WooCommerce Payments, Now with Support for Subscriptions and Saved Cards appeared first on CSS-Tricks.

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

CSS-Tricks

, , , , ,
[Top]

WebP Image Support Coming to iOS 14

Apple announced a ton of new updates at yesterday’s WWDC20 keynote address, from new hardware to updated applications. There’s lots to gawk at and enough device-envy to go around.

But there’s one little line in the Safari 14 Beta release notes that caught my eye:

Added WebP image support.

🎉🎉🎉

This excites me because WebP is a super progressive format that encodes images in lossless and lossy formats that we get with other image formats we already use, like JPEG, but at a fraction of the file size. We use WebP right here at CSS-Tricks, thanks to Jetpack and its Site Accelerator feature that serves WebP versions of the images we upload to browsers that support them. Jeremy Wagner has a great write-up on WebP and how to work with it, specifically for WordPress.

So, yes, this means WebP will be largely supported across the board (:IE-sad-trombone:) once Safari 14 ships.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Firefox IE Edge Safari
32 65 No 18 No

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
81 68 4.2-4.3 No

Even with that great support, defining fallbacks with the <picture> element is still a good idea.

<picture>   <source srcset="img/cat.webp" type="image/webp">   <source srcset="img/cat.jpg" type="image/jpeg">    <img src="img/cat.jpg" alt="Alt Text!"> </picture>

Oh, and not to be completely overshadowed, Safari 14 also squeezes in some CSS goodies, like the :is() and :where() pseudo class functions, which we linked up a couple of weeks ago. Jen Simmons picked out other key features we should be excited about.

Direct Link to ArticlePermalink

The post WebP Image Support Coming to iOS 14 appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

Can you nest @media and @support queries?

Yes, you can, and it doesn’t really matter in what order. A CSS preprocessor is not required. It works in regular CSS.

This works:

@supports(--a: b) {   @media (min-width: 1px) {     body {       background: red;     }   } }

And so does this, the reverse nesting of the above:

@media (min-width: 1px) {   @supports(--a: b) {     body {       background: green;     }   } }

You can keep going with the nesting, if it ever makes sense:

@media (min-width: 2px) {   @media (min-width: 1px) {     @supports (--a: b) {       @supports (display: flex) {         body {           background: pink;         }       }     }   } }

There is probably a point where the logic of that gets out of hand, so careful. But hey, it works. Presumably, you can “infinitely” nest at-rules.

To look at nested code like that looks a little like a CSS preprocessor is in use, but that’s not the case here. Regular ol’ CSS handles this just fine, and in fact, CSS preprocessors don’t meaningfully manipulate it at all (tested Sass, Less, and Stylus).

The post Can you nest @media and @support queries? appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]