Tag: more

Use CSS Clamp to create a more flexible wrapper utility

I like Andy’s idea here:

.wrapper {   width: clamp(16rem, 90vw, 70rem);   margin-left: auto;   margin-right: auto;   padding-left: 1.5rem;   padding-right: 1.5rem; }

Normally I’d just set a max-width there, but as Andy says:

This becomes a slight issue in mid-sized viewports, such as tablets in portrait mode, in long-form content, such as this article because contextually, the line-lengths feel very long.

So, on super large screens, you’ll get capped at 70rem (or whatever you think a good maximum is), and on small screens you’ll get full width, which is fine. But it’s those in-betweens that aren’t so great. I made a little demo to get a feel for it. This video makes it clear I think:

Direct Link to ArticlePermalink

The post Use CSS Clamp to create a more flexible wrapper utility appeared first on CSS-Tricks.

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


, , , , ,

The Web is for More Than Document Viewing

I poked at a tweet from Ken Kocienda over the weekend:

I don’t know Ken, so I feel a little bad for being harsh. But I haven’t changed how I feel. Saying “Web browsers are for viewing documents” is silly to me at this point, and suggesting it’s “the biggest wrong turn in the history of computing” feels like “your career in web development is invalid” and when people dig at what I do, I notoriously don’t take it well.

The point is silly anyway. Ken posted this on Twitter-dot-com, and then followed up with a link to job postings. I hope we all can see that Ken was literally leveraging the not-just-a-document-viewer nature of the web to help spread his message and help himself. It feels like saying “cars are bad” and then getting in your car to go to the grocery store.

Ship: sailed. The web is incredibly feature-rich far beyond viewing documents. I know the argument is that this was a mistake, not that web browsers aren’t currently capable of more. If that’s true though, what would you have the web do? Start stripping away features? Should we strip browsers down to document viewers? Maybe we just hand the keys to Facebook and we’ll just do whatever they say we should (lolz).

A super-capable open web is excellent. It means we can build things on open standards on the open web rather than things on proprietary technologies in walled gardens. It’s the better place to build things. URLs alone are a reason to build on the web.

There is still nuance to getting it right though. I enjoyed Noam Rosenthal’s baby bear porridge “Should The Web Expose Hardware Capabilities?”, which begins by discussing Alex Russell’s “Platform Adjacency Theory”:

I relate with the author’s passion for keeping the open web relevant, and with the concern that going too slow with enhancing the web with new features will make it irrelevant. This is augmented by my dislike of app stores and other walled gardens. But as a user I can relate to the opposite perspective — I get dizzy sometimes when I don’t know what websites I’m browsing are capable or not capable of doing, and I find platform restrictions and auditing to be comforting.

Maybe we just take it slow and do things carefully. Good slow. Slow, like brisket.

We’re doing that now, if by accident. Google forges ahead extremely quickly. Apple says hold on there, there are security issues here. And a smidge of vice-versa. I’d point out the other forces at work, but I guess we’re kinda down to two major browser vendor players. Not to discount Mozilla, but the choices they make with the web platform don’t affect the momentum of the web all that much at the moment.

The post The Web is for More Than Document Viewing appeared first on CSS-Tricks.

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


, , ,

More People Dipping Toes Into Web Monetization

Léonie Watson:

I do think that Coil and Web Monetization are at the vanguard of a quiet revolution.

Here’s me when I’m visiting Léonie’s site:

Browser Extension opened saying "Coil is Paying".
Enjoy the pennies!

My Coil subscription ($ 5/month) doles out money to sites I visit that have monetization set up and installed.

Other Coil subscribers deposit small bits of money directly into my online wallet (I’m using Uphold). I set this up over a year ago and found it all quick and easy to get started. But to be fair, I wasn’t trying to understand every detail of it and I’m still not betting anything major on it. PPK went as far to say it was user-hostile and I’ll admit he has some good points…

Signing up for payment services is a complete hassle, because you don’t know what you’re doing while being granted the illusion of free choice by picking one of two or three different systems — that you don’t understand and that aren’t explained. Why would I pick EasyMoneyGetter over CoinWare when both of them are black boxes I never heard of?

Also, these services use insane units. Brave use BATs, though to their credit I saw a translation to US$ — but not to any other currency, even though they could have figured out from my IP address that I come from Europe. Coil once informed me I had earned 0.42 XBP without further comment. W? T? F?

Bigger and bigger sites are starting to use it. TechDirt, is one example. I’ve got it on CodePen as well.

If this was just a “sprinkle some pennies at sites” play, it would be doomed.

I’m pessimistic at that approach. Micropayments have been done over and over and it hasn’t worked and I just don’t see it ever having enough legs to do anything meaningful to the industry.

At a quick glance, that’s what this looks like, and that’s how it is behaving right now, and that deserves a little skepticism.

There are two things that make this different

  1. This has a chance of being a web standard, not something that has to be installed to work.
  2. There are APIs to actually do things based on people transferring money to a site.

Neither of these things are realized, but if both of them happen, then meaningful change is much more likely to happen.

With the APIs, a site could say, “You’ll see no ads on this site if you pay us $ 1/month,” and then write code to make that happen all anonymously. That’s so cool. Removing ads is the most basic and obvious use case, and I hope some people give that a healthy try. I don’t do that on this site, because I think the tech isn’t quite there yet. I’d want to clearly be able to control the dollar-level of when you get that perk (you can’t control how much you give sites on Coil right now), but more importantly, in order to really make good on the promise of not delivering ads, you need to know very quickly if any given user is supporting you at the required level or not. For example, you can’t wait 2600 milliseconds to decide whether ads need to be requested. Well, you can, but you’ll hurt your ad revenue. And you can’t simply request the ads and hide them when you find out, lest you are not really making good on a promise, as trackers’n’stuff will have already done their thing.

Coil said the right move here is the “100+20” Rule, which I think is smart. It says to give everyone the full value of your site, but then give people extra if they hit monetization thresholds. For example, on this site, if you’re a supporter (not a Coil thing, this is old-school eCommerce), you can download the screencast originals (nobody else can). That’s the kind of thing I’d be happy to unlock via Web Monetization if it became easy to write the code to do that.

Maybe the web really will get monetized at some point and thus fix the original sin of the internet. I’m not really up on where things are in the process, but there is a whole site for it.

I’m not really helping, yet

While I have Coil installed and I’m a fan of all this, what will actually make a difference is having sites that actually do things for users that pay them. Like my video download example above. Maybe recipe sites offer some neat little printable PDF shopping list for people that pay them via Web Monetization. I dunno! Stuff like that! I’m not doing anything cool like that yet, myself.

If this thing gets legs, we’ll see all sorts of creative stuff, and the standard will make it so there is no one service that lords over this. It will be standardized APIs, so there could be a whole ecosystem of online wallets that accept money, services that help dole money out, fancy in-browser features, and site owners doing creative things.

The post More People Dipping Toes Into Web Monetization appeared first on CSS-Tricks.

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


, , , , ,

More on content-visibility

Back in August 2020, when the content-visiblity property in CSS trickled its way into Chrome browsers, Una Kravets and Vladimir Levin wrote about it and we covered it. The weirdest part is that to get the performance value out of it, you pair it with contain-intrinsic-size on these big chunks of the page where you insert some arbitrary guess at a height. I wrote:

That part seems super weird to me. Just guess at a height? What if I’m wrong? Can I hurt performance? Can (or should) I change that value at different viewports if the height difference between small and large screens is drastic?

Jake Archibald and Das Surma just did a video on all this and it helped clarify that a bit. You can see at about 7:30 in just how confusing it is. Jake used this massive HTML spec page as a demo, and made <section> wrappers around big chunks of HTML, and applied:

section {   content-visibility: auto; /* this is the thing that delays painting */   contain-intrinsic-size: 1px 5000px; /* this is the guess at the height of the content, and also saying width doesn't matter */ }

Apparently that 5000px isn’t the height of the element, it’s the size of the content of that element. I guess that matters because it will push that parent element taller by that number, unless the parent element overrides that with a height of its own. The magic comes from the fact that the browser will only paint¹ the first section (where it’s very likely the viewport isn’t over 5000px tall) and defer the painting on the rest. Sorta like lazy loading, but everything rather than media alone. It assumes the next section is 5000px tall, but once the top of it becomes visible, it will actually get painted and the correct height will be known. So assuming your page is just big ass blocks on top of each other, using an extremely large number should work fine there. Godspeed if your site is more complicated than that, I guess.

It’s a good video and you should watch it:

This is yet another thing where you have to inform the browser about your site so that it can Do Performance Good™. It is information that it can figure out by itself, but not until it has done things that have a performance cost. So you have to tell it up front, allowing it to avoid doing certain types of work. With responsive images, if we give images a srcset attribute with images and tell the browser in advance how big they are, including a sizes attribute with information about how our CSS behaves, it can do calculations ahead of time that only download the best possible image. Likewise, with the will-change property in CSS, we can tell the browser when we’re going to be doing movement ahead of time so it can pre-optimize for that in a way it couldn’t otherwise. It’s understandable, but a little tiresome. It’s like we need a stuff-you-need-to-know.manifest file to give browsers before it does anything else — only that would be an additional request!

The accessibility implications are important too. Steve Faulkner did a test applying content-visibility: auto to images and paragraphs:

The content is visually hidden, but in both JAWS and NVDA the hidden <img> is announced but the content of the <p> element is not. This has to do with how the img and the p element content are represented in the browser accessibility tree: The img is exposed in the accessibility tree with the alt text as the accessible name. The content of the p element is not present in the accessibility tree.

He notes that content hidden this way should not be available to screen readers, per the spec. I could see it going either way, like hide it all as if it was display: none, meaning none of it is in the accessibility tree. Or, leave it all in the accessibility tree. Right now it’s a tweener where you might see a bunch of stray images in the accessibility tree without any other context than their alt text. This is an interesting example of new tech going out with more rough edges than you might like to see.

Speaking of alt text, we all know those shouldn’t be empty when they represent important content that needs to be described to someone who can’t see them. They should be like paragraphs, says Dave:

I finally made the simplest of all connections: alt text is like a paragraph. Word pictures. Basic I know, but it helps me contextualize how to write good alt text as well as source order of my code.

I don’t want to be overly negative here! The performance gains for setting up a long-scrolling page with content-visibility is huge and that’s awesome. Being able to inform the browser about what is OK not to paint in two lines of code is pretty nice.

  1. I keep saying “paint” but I’m not sure if that’s really the right term or if it means something more specific. The spec says stuff like “allowing user agents to potentially omit large swathes of layout and rendering work until it becomes needed” (emphasis mine).

The post More on content-visibility appeared first on CSS-Tricks.

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



Jetpack 8.9: Take Donations, Capture Email Subscribers, AMP integration, and More

(This is a sponsored post.)

Jetpack 8.9 shipped on September 1 and it shows why the plugin continues to be the premier way to take a WordPress site from good to holy smokes! Several new features are packed into the release, but a few really stand out.

Take donations with a new block

The first is donations, and a quick demo of how easy it is to drop a donation form into a page is going to excite anyone who has ever had to cobble together multiple third party scripts and tools to get something like this on a site.

That’s right — it’s as easy as any other block and it connects directly to your Stripe account when you upgrade to a Jetpack paid plan. Non-profits are sure to love this, but even if you’re a plugin developer looking for a way to collect “tips” in exchange for your work, you’ll get a lot of mileage out of something like this.

I’d drop a donations block right here to show you, but if you’re so inclined (😍) we have a MVP supporter thing set up that handles that, which is powered by WooCommerce Memberships.

Collect newsletter signups and automate email marketing

Another feature that stands out is a newsletter signup form. Instead of relying on another plugin for form functionality and another to connect the form to an email newsletter service, Jetpack handles it all with a new block that not only collects subscribers, but integrates directly with Creative Mail by Constant Contact.

That means you not only take signups directly from your site, but you get a way to pull WordPress content and WooCommerce products into emails that support all kinds of automatons, like scheduled sends, action-based triggers, and multi-step marketing journeys. It’s a lot of power in a single package!

It’s worth noting that the newsletter form is in addition to a growing number of forms that are built right into Jetpack, including RSVP, contact, registration, feedback, and appointments.

AMP-ify your content

There isn’t a whole lot of details on this feature, but it certainly warrants attention. Automattic and Google have been working closely together the past several months to ship the 2.0 version of the official AMP plugin for WordPress.

The plan is for the Jetpack team to write up a detailed post sometime soon that thoroughly outlines the integration. Just a guess? Perhaps Jetpack blocks will natively support valid AMP markup in way that maintains the functionality while meeting AMP’s performance standards. We’ll see!

Jetpack 8.9 is the latest release in what’s proving to be a rapidly evolving one-stop shop for the most common and useful WordPress features that normally would require plugin overload. The past year alone has seen a slideshow block, on-site instant search, built-in customer relationship management and security monitoring — and those are just the highlights! You really can’t go wrong with Jetpack if you’re looking for the most powerful set of features in one place. Plug it in, purchase a plan, and you get access to literally dozens of features and enhancements for WordPress without having to hunt them down, one-by-one. Hey, that’s why we use Jetpack around here at CSS-Tricks… and love it!

Direct Link to ArticlePermalink

The post Jetpack 8.9: Take Donations, Capture Email Subscribers, AMP integration, and More appeared first on CSS-Tricks.

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


, , , , , , ,

More Control Over CSS Borders With background-image

You can make a typical CSS border dashed or dotted. For example:

.box {    border: 1px dashed black;    border: 3px dotted red; }

You don’t have all that much control over how big or long the dashes or gaps are. And you certainly can’t give the dashes slants, fading, or animation! You can do those things with some trickery though.

Amit Sheen build this really neat Dashed Border Generator:

The trick is using four multiple backgrounds. The background property takes comma-separated values, so by setting four backgrounds (one along the top, right, bottom, and left) and sizing them to look like a border, it unlocks all this control.

So like:

.box {   background-image: repeating-linear-gradient(0deg, #333333, #333333 10px, transparent 10px, transparent 20px, #333333 20px), repeating-linear-gradient(90deg, #333333, #333333 10px, transparent 10px, transparent 20px, #333333 20px), repeating-linear-gradient(180deg, #333333, #333333 10px, transparent 10px, transparent 20px, #333333 20px), repeating-linear-gradient(270deg, #333333, #333333 10px, transparent 10px, transparent 20px, #333333 20px);   background-size: 3px 100%, 100% 3px, 3px 100% , 100% 3px;   background-position: 0 0, 0 0, 100% 0, 0 100%;   background-repeat: no-repeat; }

I like gumdrops.

The post More Control Over CSS Borders With background-image appeared first on CSS-Tricks.

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


, , , ,

Computed Values: More Than Meets the Eye

Browser DevTools are indispensable for us front end developers. In this article, we’ll take a look at the Computed tab, a small corner of the DevTools panel that shows us big things, like how relative CSS values are resolved. We’ll also see how inheritance fits into the browser’s style computation process.

Screenshot of DevTools window for Chrome in dark mode.
The “Computed” tab is generally located in the right panel of the DevTools interface, like it is shown here in Chrome.

The content in the Computed tab is important because it shows us the values that the browser is actually using on the rendered website. If an element isn’t styled how you think it should be, looking at its computed values can help you understand why.

If you’re more accustomed to using the Styles tab (called Rules in Firefox), you may wonder how it differs from the Computed tab. I mean, they both show styles that apply to an element. The answer? The Computed tab displays an alphabetized list of resolved styles that include what is declared in your stylesheet, those derived from inheritance, and the browser’s defaults.

Screenshot of Chrome DevTools in dark mode. DOM elements are on the left and the Computed Properties information is on the right.
The “Computed” tab takes a selected element (1) and displays a list of CSS properties (2) that have been rendered, allowing each one to be expanded (3) to reveal the cascade of inherited values alongside the actual computed value (4) that is currently in use.

The Styles tab, on the other hand, displays the exact rulesets of a selected element exactly as they were written. So while the Styles tab might show you something like .subhead {font-size: 75%}, the Computed tab will show you the actual font size, or what 70% currently resolves to. For example, the actual font size for the rendered text as shown above is 13.2px.

Screenshot of Chrome DevTools in dark mode. DOM elements are on the left and the Styles information is on the right.
The “Styles” tab takes a selected element (1) and displays the ruleset (2) that is explicitly declared in the stylesheet, followed by other related rulesets that are included in the cascade (3), including those from other stylesheets (4). Notice how overridden values are crossed out, indicating that another property takes precedence.

Next, let’s briefly review the concepts of inheritance and the cascade, two things that are a huge part of how the computed values in the Computed tab are arrived at.

Crash course on inheritance and the cascade

CSS stands for Cascading Style Sheets, and that first word cascading is incredibly important to understand – the way that the cascade behaves is key to understanding CSS.


The cascade is notable because it’s the “C” in CSS. It’s the mechanism used for resolving conflicts that exist between the different sources of style declarations for a document.

For example, imagine a stylesheet that defines the width of a div twice:

div {   width: 65vw; } 
 /* Somewhere, further down */ div {   width: 85vw; }

In this specific example, the second width wins out since it is declared last. The first width could still win with !important but that’s technically breaking the cascade by brute force. The point here is that the cascade algorithm determines what styles apply to each element and prioritizes them in a predetermined order to settle on a value.

The cascade is applied for properties that are set explicitly, whether by the browser, the web developer, or the user. Inheritance comes into the picture when the output of the cascade is empty. When this happens, the computed value of a property on an element’s parent is pulled in as its own value for that property. For example, if you specify a color for an element, all child elements will inherit that color if you don’t specify theirs.

There are four key property values related to inheritance that we should get acquainted with before we plow ahead. We’ll be using these throughout the article.


In an HTML document where the highest level of the DOM tree is the <html> element, when we use the initial keyword on an element like this…

…the text color for that element is black, even though the body element is set to green. There’s the matter of the div selector having a higher specificity, however we’re interested in why initial translated to black.

In plain terms, this keyword sets the default value of a property as specified in its definition table (in the CSS specs). In this case, black happens to be the browser’s implementation of the initial color value.

I mention near the end of the article that you can learn whether or not a property is inherited by default by checking out its page on MDN. Well, you can also find the initial value for any property this way.


For non-inherited properties, this keyword forces inheritance. In the following example, the <body> element has a solid red border. The border property isn’t inherited by default, but we can tell our div to inherit the same red border declared on the <body> element by using the inherit keyword on its border property:


unset will resolve to an inherited value if a property is inherited. Otherwise, the initial value is used. This basically means unset resets a property based on whether it is inherited or not. Here’s a demo that toggles unset to show its effect on elements with different levels of specificity.


If no CSS properties are set on an element, then does it get any styles at all? You bet. It uses the browser’s default styles.

For example, the initial value for the display property for span elements is inline, but we can specify it as block in our stylesheet. Use the button in the following demo to toggle revert on both the span element’s display and color properties:

The span properly reverts to an inline element, but wait! Did you notice that the color of the span goes to a green color instead of the browser’s default black value? That’s because revert allows for inheritance. It will go as far back as the browser’s default to set the color, but since we’ve explicitly set a green color on the <body> element, that’s what is inherited.

Finding computed values in DevTools 

This is where we start talking about the computed values in DevTools. Just as with the default values of properties, the computed value of a CSS property is determined by that property’s definition table in the CSS specifications. Here’s what that looks like for the height property.

Say we use relative lengths in our CSS, like one of 10em or 70% or 5vw. Since these are “relative” to something font-size or the viewport they’ll need to get resolved to a pixel-absolute value. For example, an element with a 10% width may compute to 100px if the viewport is 1000px wide, but some other number altogether when the viewport width changes.

Screenshot of Chrome with DevTools open in dark mode on the right. CSS-Tricks is the open site, the elements tab is open in the center, and the Computed Properties values are open on the left.
A button (1) is the current selected element in DevTools (2). The declared width of the button is 100% (3), which computes to 392px (4) when the viewport is in this condition.

These values are calculated whenever the DOM is modified in a process called computed styles calculation. This is what lets the browser know what styles to apply to each page element.

Style calculations happen in multiple steps involving several values. These are documented in the CSS Cascading and Inheritance Level 4 specification and they all impact the final value we see in the Computed tab. Let’s take a look at those next.

Values and how they’re processed

The values defined for the style calculation process include the declared value, the specified value, the cascaded value, the computed value, the used value, and the actual value. Who knew there were so many, right?

Declared values

A declared value is any property declaration applies to an element. A browser identifies these declarations based on a few criteria, including:

  • the declaration is in a stylesheet that applies to the current document
  • there was a matching selector in a style declaration
  • the style declaration contains valid syntax (i.e, valid property name and value)

Take the following HTML:

<main>   <p>It's not denial. I'm just selective about the reality I accept.</p> </main>

Here are declared values that apply to the font-size of the text:

main {   font-size: 1.2em; /* this would apply if the paragraph element wasn't targeted specifically, and even then, as an inherited value, not "declared value" */ } 
 main > p {   font-size: 1.5em; /* declared value */ }

Cascaded values

The list of all declared values that apply to an element are prioritized based things like these to return a single value:

  • origin of the declaration (is it from the browser, developer, or another source?)
  • whether or not the declaration is marked ‘!important’
  • how specific a rule is (e.g, span {} vs section span {})
  • order of appearance (e.g, if multiple declarations apply, the last one will be used)

In other words, the cascaded value is the “winning” declaration. And if the cascade does not result in a winning declared value, well, then there is no cascaded value.

main > p  {   font-size: 1.2em; } 
 main > .product-description { /* the same paragraph targeted in the previous rule */   font-size: 1.2em; /* cascaded value based on both specificity and document order, ignoring all other considerations such as origin */ }

Specified values

As mentioned earlier, it is possible for the output of the cascade to be empty. However, a value still needs to be found by other means.

Now, let’s say we didn’t declare a value for a specific property on an element, but did for the parent. That’s something we often do intentionally because there’s no need to set the same value in multiple places. In this case, the inherited value for the parent is used. This is called the specified value.

In many cases, the cascaded value is also the specified value. However, it can also be an inherited value if there is no cascaded value and the property concerned is inherited, whether by default or using the inherit keyword. If the property is not inherited, then the specified value is the property’s initial value, which, as mentioned earlier, can also be set explicitly using the initial keyword.

In summary, the specified value is the value we intend to use on an element, with or without explicitly declaring it on that element. This is a little murky because the browser’s default can also become the specified value if nothing is declared in the stylesheet.

/* Browser default = 16px */ 
 main > p {   /* no declared value for font-size for the paragraph element and all its ancestors */ }

Computed values

Earlier, we discussed, briefly, how relative values needed to be resolved to their pixel-absolute equivalent. This process, as already noted, is pre-determined. For example, property definition tables have a “Computed value” field that detail how specified values, in general, are resolved.

Screenshot of the specifications section of the color property, taken from the MDN docs. The "Computed value" field is highlighted.
The specifications section of the MDN docs for the color property.

In the following example, we’re working with the em, a relative unit. Here, the final value used when rendering the element to which the property applies is not a fixed number as seen in our declared value, but something that needs to be calculated based on a few factors.

main {   font-size: 1.2em; } 
 main > p {   font-size: 1.5em; /* declared value */ }

The font-size of the paragraph element is set to 1.5em, which is relative to the font-size value of the main element, 1.2em. If main is a direct child of the body element – and no additional font-size declarations are made above that, such as by using the :root selector – we can assume that the calculation for the paragraph’s font-size will follow this approximate course:

Browser_Default_FontSize = 16px; Calculated_FontSize_For_Main = 1.2 * Browser_Default_FontSize; // 19.2px Calculated_FontSize_For_Paragraph = 1.5 * Calculated_FontSize_For_Main; // 28.8px

That 28.8px is the computed value. Here’s a demo:

Open up DevTools and check out the computed font sizes in the Computed tab.

Screenshot of Chrome DevTools open to the Element view with Computed Properties open.
The declared font-size for the main element is 1.2em, which computes to 19.2px.
Screenshot of Chrome DevTools open to the Element view with Computed Properties open.
The declared font-size for the paragraph element is 1.5em, which computes to 28.8px.

Let’s say we’re using rem units instead:

html {   font-size: 1.2em; } 
 main {   font-size: 1.5rem; } 
 div {   font-size: 1.7rem; }

The computed value of a rem unit is based on the font-size of the root HTML element, so that means that the calculation changes a little bit. In this specific case, we’re using a relative unit on the HTML element as well, so the browser’s default font-size value is used to calculate the base font-size we’ll use to resolve all our rem values.

Browser_Default_FontSize = 16px Root_FontSize = 1.2 * Browser_Default_FontSize; // 19.2px Calculated_FontSize_For_Main = 1.5 * Root_FontSize; // 28.8px Calculated_FontSize_For_Div = 1.7 * Root_FontSize; // 32.64px

Open up DevTools again for this demo:

The value, 16px, for Browser_Default_FontSize is commonly used by browsers, but this is subject to variation. To see your current default, select the <html> element in DevTools and check out the font-size that is shown for it. Note that if a value was set for the root element explicitly, just as in our example, you may have to toggle it off in the Rules tab. Next, toggle on the “Show all” or “Browser styles” (Firefox) checkbox in the Computed tab to see the default.

During inheritance, computed values are passed down to child elements from their parents. The computation process for this takes into account the four inheritance-controlling keywords we looked at earlier. In general, relative values become absolute (i.e. 1rem becomes 16px). This is also where relative URLs become absolute paths, and keywords such as bolder (value for the font-weight property) get resolved. You can see some more examples of this in action in the docs.

Used values

The used value is the final result after all calculations are done on the computed value. Here, all relative values are turned absolute. This used value is what will be applied (tentatively) in page layout. You might wonder why any further calculations have to happen. Wasn’t it all taken care of at the previous stage when specified values were processed to computed values?

Here’s the thing: some relative values will only be resolved to pixel-absolutes at this point. For example, a percentage-specified width might need page layout to get resolved. However, in many cases, the computed value winds up also being the used value.

Note that there are cases where a used value may not exist. According to the CSS Cascading and Inheritance Level 4 specification:

…if a property does not apply to an element, it has no used value; so, for example, the flex property has no used value on elements that aren’t flex items.

Actual values

Sometimes, a browser is unable to apply the used value straightaway and needs to make adjustments. This adjusted value is called the actual value. Think of instances where a font size needs to be tweaked based on available fonts, or when the browser can only use integer values during rendering and need to approximate non-integer values.

Inheritance in browser style computations

To recap, inheritance controls what value is applied to an element for a property that isn’t set explicitly. For inherited properties, this value is taken from whatever is computed on the parent element, and for non-inherited properties, the initial value for that property is set (the used value when the keyword initial is specified).

We talked about the existence of a “computed value” earlier, but we really need to clarify something. We discussed computed values in the sense of one type of value that takes part in the style resolution process, but “computed value” is also a general term for values computed by the browser for page styling. You’ll typically understand which kind we mean by the surrounding context.

Only computed values are accessible to an inherited property. A pixel-absolute value such as 477px, a number such as 3, or a value such as left (e.g. text-align: left) is ready for the inheritance process. A percentage value like 85% is not. When we specify relative values for properties, a final (i.e. “used”) value has to be calculated. Percentage values or other relative values will be multiplied by a reference size (font-size, for instance) or value (e.g. the width of your device viewport). So, the final value for a property can be just what was declared or it might need further processing to be used.

You may or may not have already noticed, but the values shown in the Computed tab of the browser will not necessarily be the computed values we discussed earlier (as in computed vs. specified or used values). Rather, the values shown are the same as returned by the getComputedStyle() function. This function returns a value which, depending on the property, will either be the computed value or the used value.

Now, let’s see some examples.

Color inheritance

main {   color: blue; }  /* The color will inherit anyway, but we can be explicit too: */ main > p {   color: inherit; }

The value computed for the color property on the main element will be blue. As color is inherited by default, we really didn’t need color: inherit for the paragraph child element because it would wind up being blue anyway. But it helps illustrate the point.

Color values undergo their own resolution process to become used values.

Font size inheritance

main {   font-size: 1.2em; }  main > p {   /* No styles specified */ }

As we saw earlier in the section on values and how they are processed, our relative value for font-size will compute to an absolute value and then be inherited by the paragraph element, even if we don’t explicitly declare it (again, font-size is inherited by default). If we had previously set styles via a global paragraph element selector, then the paragraph may gain some extra styles by virtue of the cascade. Any property values that may be inherited will be, and some properties for which the cascade and inheritance didn’t produce a value will be set to their initial value.

Percentage-specified font size inheritance

body {   font-size: 18px; }  main {   font-size: 80%; }  main > p {   /* No styles specified */ }

Similar to the previous example, the <main> element’s font-size will be absolutized in preparation for inheritance and the paragraph will inherit a font-size that is 80% of the body’s 18px value, or 14.4px.

Forced inheritance and post-layout computation

Computed values generally resolve the specified value as much as possible without layout, but as mentioned earlier, some values can only be resolved post-layout, such as percentage-specified width values. Although width isn’t an inherited property, we can force inheritance for the purpose of illustrating pre-layout and post-layout style resolution.

This is a contrived example but what we’re doing is taking an element out of the page layout by setting its display property to none. We have two divs in our markup that inherit a width, 50%, from their parent element <section>. In the Computed tab in DevTools, the computed width for the first div is absolute, having been resolved to a pixel value (243.75px for me). On the other hand, the width of the second div that was taken out of the layout using display: none is still 50%.

We’ll imagine that the specified and computed value for the parent <section> element is 50% (pre-layout) and the used value is as shown under the Computed tab – that’s 487.5px for me, post-layout. This value is halved for inheritance by the child divs (50% of the containing block).

These values have to be computed whenever the width of the browser’s viewport changes. So, percentage-specified values become percentage-computed values, which become pixel-used values.

Properties that inherit by default

How do you know if a property inherits by default or not? For each CSS property in the MDN docs, there is a specifications section that provides some extra details that include whether or not the property is inherited. Here’s what that looks like for the color property:

Screenshot of the specifications section of the color property, taken from the MDN docs. The "Inherited" field is highlighted.
The specifications section of the MDN docs for the color property.

Which properties are inherited by default and which aren’t is largely down to common sense.


Another reference option is the properties section of the W3C specs. Still another is this StackOverflow thread which may not be exhaustive at the time of writing.

Here are some examples of properties that inherit by default:

Examples of properties that do not (but which you can force to inherit with the inherit keyword):

Hopefully this gives you a solid idea of how browsers compute styles and how to reference them in DevTools. As you can see, there’s a lot that goes into a value behind the scenes. Having that context goes a long way in helping you troubleshoot your work as well as furthering your general understanding of the wonderful language we know as CSS.

Further reading

The post Computed Values: More Than Meets the Eye appeared first on CSS-Tricks.

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


, , , ,

Introducing Headless WordPress with Gatsby Cloud (Live Preview, Incremental Builds, and more!)

The Gatsby team shipped an update to its source plugin for WordPress, graduating it to a beta release. The new version brings a new set of features to Gatsby’s headless WordPress configuration, which brings together WPGraphQL and WPGatsby to power a Gatsby front-end that pulls in data from WordPress.

If you haven’t encountered these plugins before, that’s probably because they’re only available on GitHub rather than the WordPress Plugin Directory.

And if you’re wondering what the big deal is, then you’re in for a treat because this may very well be the most straightforward path to using React with WordPress. WPGraphQL turns WordPress into a GraphQL API server, providing an endpoint to access WordPress data. WPGatsby optimizes WordPress data to conform to Gatsby schema. Now, with the latest version of gatsby-source-wordpress@v4, not only is the GraphQL schema merged with Gatsby schema, but Gatsby Cloud is tossed into the mix.

That last bit is the magic. Since the plugin is able to cache data to Gatsby’s node cache, it introduces some pretty impressive features that make writing content and deploying changes so dang nice via Gatsby Cloud. I’ll just lift the feature list from the announcement:

  • Preview content as you write it with Gatsby Preview
  • Update or publish new content almost instantly with Incremental Builds, available only on Gatsby Cloud
  • Links and images within the HTML of content can be used with gatsby-image and gatsby-link. This fixes a common complaint about the original source plugin for WordPress.
  • Limit the number of nodes fetched during development, so you can rapidly make changes to your site while creating new pages and features
  • Only images that are referenced in published content are processed by Gatsby, so a large media library won’t slow down your build times 
  • Any WPGraphQL extension automatically makes its data available to your Gatsby project. This means your site can leverage popular WordPress SEOcontent modelingtranslation, and ecommerce plugins through a single Gatsby source plugin.

Live previews are super nice. But hey, check out the introduction of incremental builds. That means no more complete site rebuilds when writing content. Instead the only things that get pushed are the updated files. And that means super fast builds with fewer bugs.

Oh, and hey, if you’re interested in putting a React site together with WordPress as the CMS, Ganesh Dahal just started a two-part series today here on CSS-Tricks that provides a step-by-step walkthrough.

Direct Link to ArticlePermalink

The post Introducing Headless WordPress with Gatsby Cloud (Live Preview, Incremental Builds, and more!) appeared first on CSS-Tricks.

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


, , , , , , , , ,

We need more inclusive web performance metrics

Scott Jehl argues that performance metrics such as First Contentful Paint and Largest Contentful Paint don’t really capture the full picture of everyone’s experience with websites:

These metrics are often touted as measures of usability or meaning, but they are not necessarily meaningful for everyone. In particular, users relying on assistive technology (such as a screenreader) may not perceive steps in the page loading process until after the DOM is complete, or even later depending on how JavaScript may block that process. Also, a page may not be usable to A.T. until it becomes fully interactive, since many applications often deliver accessible interactivity via external JavaScript

Scott then jots down some thoughts on how we might do that. I think this is always so very useful to keep in mind: what we experience on our site, and what we measure too, might not be the full picture.

Direct Link to ArticlePermalink

The post We need more inclusive web performance metrics appeared first on CSS-Tricks.


, , , ,

Clipping, Clipping, and More Clipping!

There are so many things you can do with clipping paths. I’ve been exploring them for quite some time and have come up with different techniques and use cases for them — and I want to share my findings with you! I hope this will spark new ideas for fun things you can do with the CSS clip-path property. Hopefully, you’ll either put them to use on your projects or play around and have fun with them.

Before we dive in, it’s worth mentioning that this is my third post here on CSS-Tricks about clip paths. You might want to check those out for a little background:

This article is full of new ideas!

Idea 1: The Double Clip

One neat trick is to use clipping paths to cut content many times. It might sound obvious, but I haven’t seen many people using this concept.

For example, let’s look at an expanding menu:

See the Pen
The more menu
by Mikael Ainalem (@ainalem)
on CodePen.

Clipping can only be applied to a DOM node once. A node cannot have several active instances of the same CSS rule, so that means one clip-path per instance. Yet, there is no upper limit for how many times you can combine clipped nodes. We can, for example, place a clipped <div> inside another clipped <div> and so on. In the ancestry of DOM nodes, we can apply as many separate cuts as we want.

That’s exactly what I did in the demo above. I let a clipped node fill out another clipped node. The parent acts as a boundary, which the child fills up while zooming in. This creates an unusual effect where a rounded menu appears. Think of it as an advanced method of overflow: hidden.

You can, of course, argue that SVGs are better suited for this purpose. Compared to clipping paths, SVG is capable of doing a lot more. Among other things, SVG provides smooth scaling. If clipping fully supported Bézier curves, the conversation would be different. This is not the case at the time of writing. Regardless, clipping paths are very convenient. One node, one CSS rule and you’re good to go. As far as the demo above is concerned, clipping paths do a good job and thus are a viable option.

I put together short video that explains the inner workings of the menu:

Idea 2: Zooming Clip Paths

Another (less obvious) trick is to use clipping paths for zooming. We can actually use CSS transitions to animate clipping paths!

The transition system is quite astonishing in how it’s built. In my opinion, its addition to the web is one of the biggest leaps that the web has taken in recent years. It supports transitions between a whole range of different values. Clipping paths are among the accepted values we can animate. Animation, in general, means interpolation between two extremes. For clipping, this translates to an interpolation between two complete, different paths. Here’s where the web’s refined animation system shows its strength. It doesn’t only work with single values — it also works when animating sets of values.

When animating clipping paths specifically, each coordinate gets interpolated separately. This is important. It makes clipping path animations look coherent and smooth.

Let’s look at the demo. Click on an image to restart the effect:

See the Pen
Brand cut zoom
by Mikael Ainalem (@ainalem)
on CodePen.

I’m using clip-path transitions in this demo. It’s used to zoom in from one clipping path covering a tiny region going into another huge one. The smallest version of the clipping path is much smaller than the resolution — in other words, it’s invisible to the eye when applied. The other extreme is slightly bigger than the viewport. At this zoom level, no cuts are visible since all clipping takes place outside the visible area. Animating between these two different clipping paths creates an interesting effect. The clipped shape seems to reveal the content behind it as it zooms in.

As you may have noticed, the demo uses different shapes. In this case, I’m using logos of popular shoe brands. This gives you an idea of what the effect would look like when used in a more realistic scenario.

Again, here’s a video that walks through the technical stuff in fine detail:

Idea 3: A Clipped Overlay

Another idea is to use clipping paths to create highlight effects. For example, let’s say we want to use clipping paths to create an active state in a menu.

See the Pen
Skewed stretchy menu
by Mikael Ainalem (@ainalem)
on CodePen.

The demo above is not currently supported by Safari.

The clipped path above stretches between the different menu options when it animates. Besides, we’re using an interesting shape to make the UI stand out a bit.

The demo uses an altered copy of the same content where the duplicate copy sits on top of the existing content. It’s placed in the exact same position as the menu and serves as the active state. In essence, it appears like any other regular active state for a menu. The difference is that it’s created with clipping paths rather than fancy CSS styles on HTML elements.

Using clipping enables creating some unusual effects here. The skewed shape is one thing, but we also get the stretchy effect as well. The menu comes with two separate cuts — one on the left and one on the right — which makes it possible to animate the cuts with different timing using transition delays. The result is a stretchy animation with very little effort. As the default easing is non-linear, the delay causes a slight rubber band effect.

The second trick here is to apply the delays depending on direction. If the active state needs to move to the right, then the right side needs to start animating first, and vice versa. I get the directional awareness by using a dash of JavaScript to apply the correct class accordingly on clicks.

Idea 4: Slices of the Pie

How often do you see a circular expanding menu on the web? Preposterous, right!? Well, clipping paths not only make it possible but fairly trivial as well.

See the Pen
The circular menu
by Mikael Ainalem (@ainalem)
on CodePen.

We normally see menus that contain links ordered in a single line or even in dropdowns, like the first trick we looked at. What we’re doing here instead is placing those links inside arcs rather than rectangles. Using rectangles would be the conventional way, of course. The idea here is to explore a more mobile-friendly interaction with two specific UX principles in mind:

  • A clear target that is comfortable to tap with a thumb
  • Change takes place close to the focal point — the place where your visual focus is at the moment

The demo is not specifically about clipping paths. I just happen to use clipping paths to create the pen. Again, like the expandable menu demo earlier, it’s a question of convenience. With clipping and a border radius of 50%, I get the arcs I need in no time.

Idea 5: The Toggle

Toggles never cease to amaze web developers like us. It seems like someone introduces a new interpretation of a toggle every week. Well, here’s mine:

See the Pen
Inverted toggle
by Mikael Ainalem (@ainalem)
on CodePen.

The demo is a remake of this dribbble shot by Oleg Frolov. It combines all three of the techniques we covered in this article. Those are:

  • The double clip
  • Zooming clip paths
  • A clipped overlay

All these on/off switches seem to have one thing in common. They consist of an oval background and a circle, resembling real mechanical switches. The way this toggle works is by scaling up a circular clipping path inside a rounded container. The container cuts the content by overflow: hidden, i.e. double clipping.

Another key part of the demo is having two alternating versions in markup. They are the original and its yin-yang inverted mirrored copy. Using two versions instead of one is, at risk of being repetitive, a matter of convenience. With two, we only need to create a transition for the first version. Then, we can reuse most of it for the second. At the end of the transition the toggle switches over to the opposite version. As the inverted version is identical with the previous end state, it’s impossible to spot the shift. The good thing about this technique is reusing parts of the animation. The drawback is the jank we get when interrupting the animation. That happens when the user punches the toggle before the animation has completed.

Let’s again have look under the hood:

Closing words

You might think: Exploration is one thing, but what about production? Can I use clipping paths on a site I’m currently working on? Is it ready for prime time?

Well, that question doesn’t have a straightforward answer. There are, among other things, two problems to take a closer look at:

1. Browser support
2. Performance

At the time of writing there is, according to caniuse, about 93% browser support. I’d say we’re on the verge of of mass adoption. Note, this number is takes the WebKit prefix into account.

There’s also always the IE argument but it’s really no argument to me. I can’t see that it’s worthwhile to go the extra mile for IE. Should you create workarounds for an insecure browser? Your users are better off with a modern browser. There are, of course, a few rare cases where legacy is a must. But you probably won’t consider modern CSS at all in those cases.

How about performance then? Well, performance gets tricky as things mount up, but nothing that I’d say would prevent us from using clipping paths today. It’s always measured performance that counts. It’s probable that clipping, on average, causes a bigger performance hit than other CSS rules. But remember that the practices we’ve covered here are recommendations, not law. Treat them as such. Make a habit out of measuring performance.

Go on, cut your web pages in pieces. See what happens!

The post Clipping, Clipping, and More Clipping! appeared first on CSS-Tricks.