Tech News

CSS Painting Order

Css Tricks - Fri, 07/17/2020 - 9:42am

Usually, when I see terms like “painting order” or “stacking context” my brain will start to shut off and my eyes will gloss over. Not that my brain doesn’t normally shut off more often than not, but that’s another topic for another time.

Martin Robinson over at Igalia touches on these concepts using an example that’s pretty easy to grok, even for me. He starts with two boxes that overlap with negative margins.

Then he introduces a third box that’s a child of the green box. The green box is given a z-index of -1. As you might expect, both the green and yellow boxes stack below the blue box.

Here’s where my brain started melting. If the z-index of the green box stays the same at -1 but we give it’s child a massive value, say 1,000, things look… exactly the same.

I’m sure many of you can already guess (or simply flat out know) why the blue box stays on top, even though changing the yellow box’s z-index implies it should be on top instead, but I sure didn’t. Martin found the technical answer in the CSS2 specification buried deep down in Appendix E, which he graciously linked up — otherwise, I’m sure I’d never have found it.

We learn from the Appendix E that a stacking context is an atomically painted collection of page items. What does this mean? To put it simply, it means that things inside a stacking context are painted together, as a unit, and that items outside the stacking content will never be painted between them. Having an active z-index is one of the situations in CSS which triggers the creation of a stacking context. Is there a way we can adjust our example above so that the third element belongs to the same stacking context as the first two elements? The answer is that we must remove it from the stacking context created by the second element.

So, yeah. As long as the yellow box is a child of the green box, the two form a stacking context that the blue box has no part of. Getting yellow above blue requires removing it from blue’s stacking context.

That’s the crux of Martin’s post, but he takes it even further and it’s worth heading over there. If you do, you’ll see how stacking order leads to some bonafide CSS tricks.

It’s not the first time we’ve linked up proof that z-index is not a level playing field so I’m going to try to commit this to memory the next (and inevitable) time I wrestle with stacking elements.

Direct Link to ArticlePermalink

The post CSS Painting Order appeared first on CSS-Tricks.

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

CSS Painting Order

Css Tricks - Fri, 07/17/2020 - 9:42am

Usually, when I see terms like “painting order” or “stacking context” my brain will start to shut off and my eyes will gloss over. Not that my brain doesn’t normally shut off more often than not, but that’s another topic for another time.

Martin Robinson over at Igalia touches on these concepts using an example that’s pretty easy to grok, even for me. He starts with two boxes that overlap with negative margins.

<div class="blue box">1</div> <div class="green box">2</div>

Then he introduces a third box that’s a child of the green box. The green box is given a z-index of -1. As you might expect, both the green and yellow boxes stack below the blue box.

<div class="blue box">0</div> <div class="green box" style="position: relative; z-index: -1;">-1 <div class="yellow box">-1</div> </div>

Here’s where my brain started melting. If the z-index of the green box stays the same at -1 but we give it’s child a massive value, say 1,000, things look… exactly the same.

<div class="blue box">0</div> <div class="green box" style="position: relative; z-index: -1;">-1 <div class="yellow box" style="position: relative; z-index: 1000;">1000</div> </div>

I’m sure many of you can already guess (or simply flat out know) why the blue box stays on top, even though changing the yellow box’s z-index implies it should be on top instead, but I sure didn’t. Martin found the technical answer in the CSS2 specification buried deep down in Appendix E, which he graciously linked up — otherwise, I’m sure I’d never have found it.

We learn from the Appendix E that a stacking context is an atomically painted collection of page items. What does this mean? To put it simply, it means that things inside a stacking context are painted together, as a unit, and that items outside the stacking content will never be painted between them. Having an active z-index is one of the situations in CSS which triggers the creation of a stacking context. Is there a way we can adjust our example above so that the third element belongs to the same stacking context as the first two elements? The answer is that we must remove it from the stacking context created by the second element.

So, yeah. As long as the yellow box is a child of the green box, the two form a stacking context that the blue box has no part of. Getting yellow above blue requires removing it from green’s stacking context.

That’s the crux of Martin’s post, but he takes it even further and it’s worth heading over there. If you do, you’ll see how stacking order leads to some bonafide CSS tricks.

It’s not the first time we’ve linked up proof that z-index is not a level playing field so I’m going to try to commit this to memory the next (and inevitable) time I wrestle with stacking elements.

Direct Link to ArticlePermalink

The post CSS Painting Order appeared first on CSS-Tricks.

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

Develop, Preview, Test

Css Tricks - Fri, 07/17/2020 - 8:03am

Guillermo:

I want to make the case that prioritizing end-to-end (E2E) testing for the critical parts of your app will reduce risk and give you the best return. Further, I’ll show how you can adopt this methodology in mere minutes.

His test is:

  1. Spin up Puppeteer (Headless Chrome) and Chai
  2. Go to the homepage
  3. Test if the homepage has his name on it.

YES.

Just one super basic integration goes a long way. If your site spins up, returns a page, and renders stuff on it that you expect, a lot is going right. Then, once you have that, you can toss in a handful more where you navigate around a little and click some things. And, if it still works, you’re in pretty good shape.

I’ve had a little trouble with Cypress over the years, but you’ll probably have better luck than I did. Overall, I think it’s the nicest player in the integration test market.

Direct Link to ArticlePermalink

The post Develop, Preview, Test appeared first on CSS-Tricks.

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

Develop, Preview, Test

Css Tricks - Fri, 07/17/2020 - 8:03am

Guillermo:

I want to make the case that prioritizing end-to-end (E2E) testing for the critical parts of your app will reduce risk and give you the best return. Further, I’ll show how you can adopt this methodology in mere minutes.

His test is:

  1. Spin up Puppeteer (Headless Chrome) and Chai
  2. Go to the homepage
  3. Test if the homepage has his name on it.

YES.

Just one super basic integration goes a long way. If your site spins up, returns a page, and renders stuff on it that you expect, a lot is going right. Then, once you have that, you can toss in a handful more where you navigate around a little and click some things. And, if it still works, you’re in pretty good shape.

I’ve had a little trouble with Cypress over the years, but you’ll probably have better luck than I did. Overall, I think it’s the nicest player in the integration test market.

Direct Link to ArticlePermalink

The post Develop, Preview, Test appeared first on CSS-Tricks.

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

On dependency

Css Tricks - Thu, 07/16/2020 - 2:46pm

Rob Weychert:

But I can’t host your site or even my own site. I didn’t build the CMS. Other people made the hardware and software I use to generate and optimize images. Other people made the fonts. Other people standardized the digital formats for those images and fonts. I didn’t write the HTML and CSS specifications, nor the browsers that interpret them, nor the operating systems that run the browsers. I didn’t solder the circuit boards. And so on.

There is so much hardware and software behind a website to the extent that there is certainly no one person who understands it all. We build everything on each other’s shoulders. (Related: I, Website)

But we can exert some influence about what technology we choose to use. Rob has three major considerations:

  1. Complexity: How complex is it, who absorbs the cost of that complexity, and is that acceptable?
  2. Comprehensibility: Do I understand how it works, and if not, does that matter?
  3. Reliability: How consistently and for how long can I expect it to work?

I like that system. But even more, I like that he has a system at all. I bet most people don’t. That’s why “just npm install the problem away” is such a reliable conference joke.

Direct Link to ArticlePermalink

The post On dependency appeared first on CSS-Tricks.

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

On dependency

Css Tricks - Thu, 07/16/2020 - 2:46pm

Rob Weychert:

But I can’t host your site or even my own site. I didn’t build the CMS. Other people made the hardware and software I use to generate and optimize images. Other people made the fonts. Other people standardized the digital formats for those images and fonts. I didn’t write the HTML and CSS specifications, nor the browsers that interpret them, nor the operating systems that run the browsers. I didn’t solder the circuit boards. And so on.

There is so much hardware and software behind a website to the extent that there is certainly no one person who understands it all. We build everything on each other’s shoulders. (Related: I, Website)

But we can exert some influence about what technology we choose to use. Rob has three major considerations:

  1. Complexity: How complex is it, who absorbs the cost of that complexity, and is that acceptable?
  2. Comprehensibility: Do I understand how it works, and if not, does that matter?
  3. Reliability: How consistently and for how long can I expect it to work?

I like that system. But even more, I like that he has a system at all. I bet most people don’t. That’s why “just npm install the problem away” is such a reliable conference joke.

Direct Link to ArticlePermalink

The post On dependency appeared first on CSS-Tricks.

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

Backdrop Filter effect with CSS

Css Tricks - Thu, 07/16/2020 - 10:35am

I love these little posts where some tricky-looking design is solved by a single line of CSS using a little-known property. In this case, the design is a frosted glass effect and the CSS property is backdrop-filter.

The approach? Easy peasy:

.container { backdrop-filter: blur(10px); }

The comments in the post are worth looking into because they address cross-browser support. Coverage is actually pretty good. Caniuse shows 83% global coverage with Firefox (and, predictably, Internet Explorer) lacking support. One commenter offered a nice fallback, along with a small tweak that desaturates the effect:

.container { background: rgba(0,0,0,0.8); backdrop-filter: saturate(180%) blur(10px); }

Nice. But we can take it a little further by sprinkling @supports in there, as demonstrated in our background-filter Almanac entry:

.container { background: rgba(0,0,0,0.8); } @supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) { .container { -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); } }

Notice the -webkit prefix in there. It’s still worth using it in production, though that’s not a big deal assuming you’re wired up with Autoprefixer. Here’s the demo from the Almanac:

CodePen Embed Fallback

OK, so maybe not the one-line solution it appeared to be. But hey, it’s cool that this sort of thing is relatively trivial in CSS.

Direct Link to ArticlePermalink

The post Backdrop Filter effect with CSS appeared first on CSS-Tricks.

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

Irregular-shaped Links with Subgrid

Css Tricks - Thu, 07/16/2020 - 4:44am

Michelle Barker covers a situation where you need offset rectangles part of a clickable area. The tricky part is having just the rectangles be clickable. That rules out using some parent element and making the whole larger encompassing rectangle clickable, which is a common (but equally tricky) pattern.

Kicking one rectangle outside the bounds of the linked one with absolute positioning could work, but Michelle takes a path here that lays everything out on a grid, then uses pointer-events to get the click areas just right. Feels more robust to me.

CodePen Embed Fallback

Yet another good example of why we need subgrid everywhere, stat.

Direct Link to ArticlePermalink

The post Irregular-shaped Links with Subgrid appeared first on CSS-Tricks.

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

Tradeoffs and Shifting Complexity

Css Tricks - Wed, 07/15/2020 - 1:37pm

This is a masterclass from Dave:

After you hit the wall of unremovable complexity, any “advances” are a shell game, making tradeoffs that get passed down to the user … you get “advances” by shifting where the complexity lives.

You don’t get free reductions in complexity. In CSS land, you don’t get to pick some styling strategy and have all your troubles go away. This is plenty of nuance here, but largely whatever technologies you pick, you’re just placing the complexity in different buckets.

CodePen Embed Fallback

The best we can hope for is picking buckets that feel the most comfortable and productive for us and our teams.

Direct Link to ArticlePermalink

The post Tradeoffs and Shifting Complexity appeared first on CSS-Tricks.

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

Making lil’ me

Css Tricks - Wed, 07/15/2020 - 9:09am

Cassie Evans made a lovely illustration of herself and then used Greensock to add a flourish of animations to polish it off. Cassie wrote a series of posts about how she did it:

In this post we’ll cover how to get values from the mouse movement and plug them into an animation. This is my favourite thing about SVG animation. Not mouse movement in particular, but interactivity. Exporting animation as an mp4 is cool and all. But you can’t play with it. Animating on the web opens up so many cool possibilities!

Speaking of combining great illustrations with impressive animations, Jhey Tompkins recently shared a bunch of tips he’s learned from building complex CSS illustrations. This first piece of advice? It takes time and have patience. I’m sure he needed all the patience in the world to pull off his animated Matryoshka dolls.

Direct Link to ArticlePermalink

The post Making lil’ me appeared first on CSS-Tricks.

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

Make Jamstack Slow? Challenge Accepted.

Css Tricks - Wed, 07/15/2020 - 4:46am

“Jamstack is slowwwww.” That’s not something you hear often, right? Especially, when one of the main selling points of Jamstack is performance. But yeah, it’s true that even a Jamstack site can suffer hits to performance just like any other site. 

Don’t think that by choosing Jamstack you no longer have to think about performance. Jamstack can be fast — really fast — but you have to make the right choices. Let’s see if we can spot some of the poor decisions that can lead to a “slow” Jamstack site.

To do that, we’re going to build a really slow Gatsby site. Seems strange right? Why would we intentionally do that!? It’s the sort of thing where, if we make it, then perhaps we can gain a better understanding of what affects Jamstack performance and how to avoid bottlenecks.

We will use continuous performance testing and Google Lighthouse to audit every change. This will highlight the importance of testing every code change. Our site will start with a top Lighthouse performance score of 100. From there, we will make changes until it scores a mere 17. It is easier to do than you might think!

Let’s get started!

Creating our Jamstack site

We are going to use Gatsby for our test site. Let’s start by installing the Gatsby CLI installed:

npm install -g gatsby-cli

We can up a new Gatsby site using this command:

gatsby new slow-jamstack

Let’s cd into the new slow-jamstack project directory and start the development server:

cd slow-jamstack gatsby develop

To add Lighthouse to the mix, we need a Gatsby production build. We can use Vercel to host the site, giving Lighthouse a way to runs its tests. That requires installing the Vercel command-line tool and logging in:

npm install -g vercel-cli vercel

This will create the site in Vercel and put it on a live server. Here’s the example I’ve already set up that we’ll use for testing.

We’ve gotta use Chrome to access directly from DevTools and run a performance audit. No surprise here, the default Gatsby site is fast:

A score of 100 is the fastest you can get. Let’s see what we can do to slow it down.

Slow CSS

CSS frameworks are great. They can do a lot of heavy lifting for you. When deciding on a CSS framework use one that is modular or employs CSS-in-JS so that the only CSS you need is what’s loaded.

But let’s make the bad decision to reach for an entire framework just to style a button component. In fact, let’s even grab the heaviest framework while we’re at it. These are the sizes of some popular frameworks:

FrameworkCSS Size (gzip)Bootstrap68kb (12kb)Bulma73kb (10kb)Foundation30kb (7kb)Milligram10kb (3kb)Pure17kb (4kb)SemanticUI146kb (20kb)UIKit33kb (6kb)

Alright, SemanticUI it is! The “right” way to load this framework would be to use a Sass or Less package, which would allow us to choose the parts of the framework we need. The wrong way would be to load all the CSS and JavaScript files in the <head> of the HTML. That’s what we’ll do with the full SemanticUI stylesheet. Plus, we’re going to link up jQuery because it’s a SemanticUI dependency.

We want these files to load in the head so let’s jump into the html.js file. This is not available in the src directory until we run a command to copy over the default from the cache:

cp .cache/default-html.js src/html.js

That gives us html.js in the src directory. Open it up and add the required stylesheet and scripts:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.css"></link> <script src="https://code.jquery.com/jquery-3.1.1.js"></script> <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.js"></script>  

Now let’s push the changes straight to our production URL:

vercel --prod

OK, let’s view the audit…

Zoikes! A 33% reduction!

We have reduced the speed of the site down to a score of 66. Remember that we are not even using this framework at the moment. All we have done is load the files in the head and that reduced the performance score by one-third. Our Time to Interactive (TTI) jumped from a quick 1.9 seconds to a noticeable 4.9 seconds. And look at the possible savings we could get with from Lighthouse’s recommendations.

Slow marketing dependencies

Next, we are going to look at marketing tags and how these third-party scripts can affect performance. Let’s pretend we work with a marketing department and they want to start measuring traffic with Google Analytics. They also have a Facebook campaign and want to track it as well. 

They give us the details of the scripts that we need to add to get everything working. First, for Google Analytics:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-4369823-4"></script> <script   dangerouslySetInnerHTML={{ __html: `   window.dataLayer = window.dataLayer || [];   function gtag(){dataLayer.push(arguments);}   gtag('js', new Date());   gtag('config', 'UA-4369823-4');   `}} />

Then for the Facebook campaign:

<script   dangerouslySetInnerHTML={{ __html: `     !function(f,b,e,v,n,t,s)     {if(f.fbq)return;n=f.fbq=function(){n.callMethod?     n.callMethod.apply(n,arguments):n.queue.push(arguments)};     if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';     n.queue=[];t=b.createElement(e);t.async=!0;     t.src=v;s=b.getElementsByTagName(e)[0];     s.parentNode.insertBefore(t,s)}(window, document,'script',     'https://connect.facebook.net/en_US/fbevents.js');     fbq('init', '3180830148641968');     fbq('track', 'PageView');     `}} /> <noscript><img height="1" width="1" src="https://www.facebook.com/tr?id=3180830148641968&ev=PageView&noscript=1"/></noscript>

We’ll place these scripts inside html.js, again in the <head> section, before the closing </head> tag.

Just like before, let’s push to Vercel and re-run Lighthouse:

vercel --prod

Wow, the site is already down to 51 and all we’ve done is tack on one framework and a couple of measly scripts. Together, they/ve reduced the score by a whopping 49 points, nearly half of where we started.

Slow images

We haven’t added any images to the site yet but we know we absolutely would in a real-life scenario. We are going to add 100 images to the page. Sure, 100 is a lot for a single page but, then again, we know that images are often the biggest culprits of bloated web pages so we might as well let them shine.

We’ll make things a little worse by hot loading the images directly from https://placeimg.com instead of serving them on our own server.

Let’s crack open index.js and drop this code in, which will loop through 100 instances of images:

const IndexPage = () => {   const items = []   for(var i = 0; i < 100; i++) {     const url = `http://placeimg.com/640/360/any?=${i}`     items.push(<img key={i} alt={i} src={url} />)   }      return (     <Layout>       // ...       {items}       // ...     </Layout>   ) }

The 100 images are all different and will all load as the page loads, thereby blocking the rendering. OK, let’s push to Vercel and see what’s up.

vercel --prod That score deserves a sad trombone. &#x1f3ba;

OK, we now have a very slow Jamstack site. The images are blocking the rendering of the page and the TTI is now a whopping 16.5 seconds. We have taken a very fast Jamstack site and dropped it to a Lighthouse score of 17 — a reduction of 83 points!

Now, you may be think that you would never make these poor decisions when building an app. But you are missing the point. Every choice we make has an impact on performance. It’s a balance and performance does not come free. Even on Jamstack sites.

Making Jamstack fast again

You have seen that we cannot ignore client-side performance when using Jamstack. 

So why do people say that Jamstack is fast? Well, the main advantage of Jamstack — or using static site generators in general — is caching. Static files are cached on the edge reducing Time to First Byte (TTFB).

This is always going to be faster than going to a single-origin web server before generating the page. This is a great feature of Jamstack and gives you a fighting chance to create a page that can hit 100 in Lighthouse. (But, hey, as a side note, remember that great scores aren’t always indicative of an actual user experience.)

See, I told you we could make Jamstack slow! There are also many other things that can slow it down, but hopefully this drives home the point.

While we’re talking about performance, here are a few of my favorite performance articles on here at CSS-Tricks:

The post Make Jamstack Slow? Challenge Accepted. appeared first on CSS-Tricks.

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

Netlify Does Cache Invalidation For You

Css Tricks - Tue, 07/14/2020 - 2:46pm

This is one of my favorite Netlify features. Say you’re working on a site and you change as asset like a CSS, JavaScript, or image file. Ya know, like do our job. On Netlify, you don’t have to think about how that’s going to play out with deployment, browsers, and cache. Netlify just handles it for you.

Netlify calls this Instant Cache Invalidation, part of the “rocketjuice” of Netlify.

On all the sites I work on that aren’t on Netlify, I do have to think about it (ugh). If you look at this very websites source, you’ll see a link to a stylesheet something like this:

<link href="https://css-tricks.com/wp-content/themes/CSS-Tricks-17/style.css?cache_bust=1594590986788" rel="stylesheet">

See that ?cache_bust= stuff at the end of the stylesheet URL? Those are just gibberish characters I put into that URL manually (based on a Date() call) so that when I push a change to the file, it breaks both the CDN and people’s own browser cache and they get the new file. If I didn’t do that, the changes I push won’t be seen until all the cache expires or is manually removed by users, which is… bad. I might be fixing a bug! Or releasing a new feature! It’s extra bad because that CSS might go along with some HTML which doesn’t cache as aggressively and could lead to a mismatch of HTML and expected CSS.

I work on some sites where I change that cache-busting string by hand because I’m too lazy to automate it. Usually, I do automate it though. I recently shared my Gulpfile which I hand-wrote, and part of which deals with this cache-busting. It is work to write, work to maintain, and work to use during development. You can even read the comments on that post and see other people’s strategies for doing the same thing that are different than how I do it. Errrrrrybody be cache-busting.

Not on Netlify.

Again, you change an asset, push it up, Netlify knows it’s changed and does all the cache busting for you. So your stylesheet can be linked up like:

<link href="dont-even-worry-about-it.css" rel="stylesheet" />

The post Netlify Does Cache Invalidation For You appeared first on CSS-Tricks.

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

Open Prioritization

Css Tricks - Tue, 07/14/2020 - 4:37am

Like Kickstarter, but for Web Platform Features.

That’s about the quickest way to sum up Open Prioritization from Igalia. Igalia is an independent company that works on browsers. They literally commit to all the different open source browsers to implement (and fix) features that we all use. Now they are asking: what browser features are important to you? Are they important enough for you to pledge some money to get it implemented?

I think it’s a clever idea and I’d love for it to get enough legs that it actually starts working and that enough money comes in that Igalia is able to throw resources behind the features that people have voted are the most important with their money.

For example, I pledged $20 to get d: path(); support in Firefox. Heck yeah, that would be awesome! If it starts edging closer to that goal, I know I’d be tempted to up that to get it over the line, but some momentum needs to start building first.

Is this all sunshine and roses? Perhaps not. Some of the pushback I’ve heard so far is about the message this sends to the massive companies behind these browsers. Rather than the message being “please fix these features of your incredibly important piece of software, it will make things better for everyone including you,” the message becomes, “I guess we’ll spend our own money and band together to try to get a third-party to fix your software for you.” A bit like when school teachers need to buy their own classroom supplies.

Rachel Andrew talked to Brian Kardell about some of this nuance in her coverage on Smashing Magazine.

And, oh hey, in related news, I recently came across this Web Platform Contribution Guide. What a nice resource for people looking to get into helping the web literally and directly.

Direct Link to ArticlePermalink

The post Open Prioritization appeared first on CSS-Tricks.

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

Running spot instances effectively with Amazon EKS

Css Tricks - Mon, 07/13/2020 - 12:12pm

I know this is a little outside the normal scope of CSS-Tricks stuff, but I find the whole concept of spot instances fascinating. Here’s the gist from a very-non-expert (me). You can just buy and pay for web servers, for example, Amazon EC2. You can save a bunch of money if you buy them as “reserved instances” meaning you agree ahead of time you’ll need it for a long time (like a year) and prepay some or all of it.

There is a way to save way more money though, and that’s to use spot instances. Blake Stoddard:

Spot instances give us the ability to get the compute we need at an even deeper discount than a 1-year RI or savings plan rate would, without the same commitment. Combine the price with seamless integration with auto-scaling groups and it makes them a no-brainer for most of our workloads.

The big catch with spot instances? AWS can take them back from you with a two-minute notice.

With a spot instance, you ask for a web server and get one, but it can be ripped away from you at any time. No wonder it’s so cheap, eh?

In order to take advantage of this, you have to know what you’re doing (which rules me out, but thankfully I work with smart people). You can’t put everything on spot instances because some things need to be highly available, and that will depend on what you’re doing. But even more so than the cost savings, that’s what I like about the idea of spot instances: it teaches you to build in a resilient way. If you can build your site on a system where the servers themselves can get taken away from you at any moment and still offer a reliable service, that’s a seriously resilient foundation.

Direct Link to ArticlePermalink

The post Running spot instances effectively with Amazon EKS appeared first on CSS-Tricks.

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

My Long Journey to a Decoupled WordPress Gatsby Site

Css Tricks - Mon, 07/13/2020 - 4:32am

As a professional research biologist, my playground used to be science laboratories filled with microscopes, petri dishes, and biology tools. Curiosity leads many scientists on their journey to discoveries. Mine led me to web design. I used to try learning HTML on my lab desktop while centrifuging extraction samples or waiting for my samples to thaw or freeze. These wait times are valuable for writing experiment notes and even learn a new skill. For me, this meant learning basic HTML through editors, like HomeSite and later Dreamweaver, as well as many other online resources.

After leaving my science lab desk about a decade ago, I found a new playground. I was introduced to WordPress by a local web developer friend. This changed the course of my life. Learning web design is no longer a downtime activity — it has become the main activity of my daily life.

My first step: Learning theme development

I call myself a WordPress enthusiast and an avid WordPress user. I entered into the world of WordPress by learning to hack themes, my virtual guru“Building Themes from Scratch Using Underscores” by Morten Rand-Hendriksen. While learning to develop themes, I must have watched this tutorial countless times and quickly it became my go-to reference. While doing my learning projects, I often referred to Morten’s GitHub repository to learn from his themes. For my personal sites, I used my own themes which are inspired by Morten’s, like Kuhn, Popper and others.

I also learned how to build plugins and widgets for my own site, but I mostly stayed within theming. I built themes for my personal sites. My personal sites are like my three-ring binders: one for every subject area. My sites discourage search engines and are designed for archiving my personal learning and posting notes. This habit of writing and documenting every aspect of my projects was inspired by “Just Write” by Sara Soueidan.

A call to Learn JavaScript deeply

It all started with Matt Mullenweg‘s  call for WordPress developers to “learn JavaScript deeply” during the 2015 State of the Word address and the subsequent announcement of the Gutenberg block editor. Until then, I was a happy WordPress user and an aspiring WordPress developer. It was reported that JavaScript and API-driven Interfaces are the future of WordPress. Like other WordPress enthusiasts, I also acknowledged that JavaScript was  a must-have skill for WordPress development.

Thus, began my own JavaScript learning journey and road map. I used Zell Liew’s article “Learning JavaScript — where should you start and what to do when you’re stuck?”

Let me share my learning journey with you.

I started by looking at React and REST API-based themes

Since the official integration of the REST API in WordPress core, a few React-based themes have started popping up.

In my opinion, these themes appeared to be experimental. When the Foxhound theme was released, it was covered in CSS-Tricks as well as WordPress Tavern. I downloaded it to my test site, and it worked fine; however, I could not hack and learn from it given my limited familiarity with JavaScript and React.

I started digging into React

I used Robin Wieruch’s article “JavaScript fundamentals before learning React” as my JavaScript/React learning road map. While struggling to learn and understand React routing, I discovered Gatsby which utilizes @reach/router as a built-in feature, making routing a breeze. In my brief exploratory research, I learned that Gatsby is indeed a “React-based framework that helps developers build blazing fast websites and apps.” This led me to learn Gatsby while continuing to make progress on React. After a while, I immersed myself in my Gatsby projects and only occasionally returned to learning basic JavaScript and React.

I picked up Gatsby

Given that I had already done several small learning projects in React, understanding Gatsby was natural. Gatsby is said to be aimed at developers and not users. I did not find it that hard to learn and run my own simple Gatsby test sites.

Gatsby’s documentation and tutorials are well-written, helpful, and easy to follow. I decided to learn Gatsby using its tutorials and completing all eight parts as a means of “learning by doing.” While working on my projects, I consulted other guides and tutorial posts. The following two guides helped me to understand build concepts, add functionality and put together a reasonable Gatsby demo site:

For styling React components, there are several options which are covered on CSS-Trick. Some options include local inline CSS-in-JS, styled components and modular CSS. Gatsby components can also be styled with Sass using gatsby-plugin-sass, which makes the code more readable. Because of its familiarity and code readability, I chose styling with Sass; however, I recognize the value of CSS modules as well.

Resources for integrating Gatsby and WordPress

My Gatsby learning didn’t stop there. In fact, Gatsby has been the most significant part of my learning curve more recently. Here’s everything I found throughout my learning journey that I hope will serve you as well on your own journey.

There are many sites already running on Gatsby. Those who have migrated to Gatsby seem to be happy, especially with the blazingly fast speed and the improved security it offers.

Commenting in Gatsby

WordPress has natively supported comments for a long, long time. Gatsby sites are serverless-static, so posting comments is an issue since they are dynamic and requires a client side service.

Some Gatsby and React developers seem to leave commenting and interactions on their own personal sites to Twitter. Others seem to reach for Disqus. If you are interested, this Northstack tutorial describes in detail how to bring WordPress comments over to Gatsby.

WordPress Gatsby themes

I first became aware of WordPress ported Tabor for Gatsby theme from WordPress Tavern. It was developed by Rich Tabor and is freely available on GitHub (demo). From there, two WordPress-inspired Gatsby themes became available through the Gatsby Theme Jam project. One was by Alexandra Spalato called Gatsby Theme WordPress Starter (demo) and the other by Andrey Shalashov called WordPress Source Theme (demo).

In 2019, a team of Gatsby and WPGraphQL developers led by Jason Bahl, Muhammad Muhsin, Alexandra Spalato, and Zac Gordon announced a project that ports WordPress themes to Gatsby. Zac, talking to WordPress Tavern, said the project would offer both free and paid premium themes. At the time of this writing, five themes were listed with no free download.

Decoupled Gatsby WordPress starters

The current Gatsby starer library lists ten WordPress-compatible starter themes, including a more recent one by Henrik Wirth that ports the WordPress Twenty Twenty theme — stylesheets and fonts — to Gatsby. Although the theme is still a work-in-progress with some limitations (e.g. no support for tags, monthly archives, and comments). Nevertheless, it is a great project and uses a new experimental Gatsby Source plugin for WordPress.

Another popular starter is gatsby-starter-wordpress by Gatsby Central.

Gatsby WordPress themes from GitHub

There are other popular Gatsby themes that are available at GitHub. The Twenty Nineteen WordPress Gatsby Theme is a port of the Twenty Nineteen WordPress Theme by Zac Gordon and Muhammad Muhsin.

Experimental plugins

There are also two new GraphQL plugins for WordPress that are under development and only available on GitHub at the moment. One is Gatsby Source WordPress Experimental by Tyler Barnes. This is a re-written version of current Gatsby Source WordPress plugin using WPGraphQL for data sourcing, as well as a custom WPGatsby plugin that transforms WPGraphQL schema in Gatsby-specific ways.

The other one is Gatsby WordPress Gutenberg which is still being developed by Peter Pristas. Its documentation is available over at the GatsbyWPGutenberg Docs site.

Step-by-step guides

Despite the ongoing progress in Gatsby WordPress theme development, I could not locate any detailed how-to guides written for beginners like me. Mohammad Mohsin wrote up a thorough guide over at Smashing magazine in 2018, explaining how he developed his Celestial React theme using the WordPress REST API. The other tutorial is another one he wrote about porting the Twenty Nineteen WordPress Theme to Gatsby, which uses WPGraphQL for WordPress data sourcing.

More recently, there have been two additional guides that I’ve benefited from:

Finally, my own partially ported Gatsby site

Everything covered so far is what has fueled me to create my own WordPress Gatsby site. While it was a large technical task, the guides I’ve referenced, in addition to the experimental plugins and existing documentation for Gatsby made it so much easier than if I had attempted to figure it out on my own.

Here is the result. While it’s still a work in progress, it’s awesome to see it working. I’ve written up a complete step-by-step walkthrough on how I made it, which will publish next week here on CSS-Tricks. So stay tuned!

What’s next on the horizon for Gatsby and WordPress?

I am still keeping my eyes on the two experimental WordPress plugins I mentioned earlier. I plan to revisit the project once those are officially released, hopefully in the WordPress Plugin Directory. This recent tweet thread highlights the current status of porting content from the WordPress block editor to a decoupled WordPress Gatsby theme.

Has anyone successfully used the block editor with a decoupled #WordPress setup? I haven’t tried but have heard some rumblings it doesn’t work, or doesn’t work well. Curious to hear from folks.

— Rachel Cherry (@bamadesigner) May 14, 2020

In a recent WordCamp Spain 2020 session, Matt Mullenweg said that the demand for decoupled WordPress sites is growing:

But for people who are building more advanced applications or have some sort of constraint on their website where they need the React frontend, I think the decoupled use case of WordPress is stronger than ever. 

Dan Abramov agrees:

This hits the nail on the head. And is 100% matching our long term thinking. Client-side-only is not sustainable. We need to move more stuff to the server, but without sacrificing seamless composition of interactive pieces. https://t.co/O4LX8JacRo

— Dan Abramov (@dan_abramov) May 10, 2020

Taking with Sarah Gooding of WPTavern, Gatsby WP Themes project members Zac Gordon and Jason Bahl also confessed that the “most current Gatsby WordPress themes are directed for businesses and developers, they are not suitable for beginners.” Let’s hope the future fixes that!

My personal take

Based on my very limited experience, I think that currently available Gatsby WordPress themes are not ready for prime time use for users like me. Yeah, it is exciting to try something on the bleeding edge that’s clearly in the minds of many WordPress users and developers. At the same time, the constantly evolving work being done on the WordPress block editor, WPGraphQL and Gatsby source WordPress plugins makes it difficult to predict where things are going and when it will settle into a state where it is safe to use in other contexts. Until then, it’s a frustrating experience to work on something only to have the API or the interface change on you.

For my own personal uses, a normal Gatsby site is enough, I could get content with Markdown files without any hassles associated with decoupling WordPress. For larger agency sites… I can see why having a decoupled solution would make a lot of sense for them and their clients.

Remember, I’ll be sharing my tutorial next week — see you then!

The post My Long Journey to a Decoupled WordPress Gatsby Site 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!)

Css Tricks - Mon, 07/13/2020 - 4:32am

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.

Lazy Loaded Prefill Embeds

Css Tricks - Mon, 07/13/2020 - 3:24am

Lemme sum this up:

  • CodePen has Embedded Pens. Build a Pen on CodePen, embed it on any other site.
  • We also offer Prefill Embeds, which remove that first step. With Prefill Embeds, the Pen doesn’t need to exist on CodePen at all. You pass in the code and settings you want to appear in the embed via code blocks sitting on the page (progressive enhancement!). Now that code can live in your Git repo or database, which might offer a more desirable level of control.
  • Stephen Shaw details how these Prefill Embeds can be created on-demand through user interaction (e.g. click a “Run this code” button) so they are only there when a user wants to see them. This is a super lightweight way to add optional interactivity to any blog post or documentation.

I’ll put an example right here in this blog post:

<h1>Hello from HTML</h1> html { background: black; color: white; text-align: center; } h1::after { content: " / CSS!"; } document.querySelector("h1").innerText += " / JavaScript"; Array.from(document.querySelectorAll("[data-prefill]"), (el) => { // Create a Click to Run button const button = document.createElement("button"); button.innerHTML = "Click to Run Code"; button.classList.add("button"); button.classList.add("prefill-click-to-run"); el.appendChild(button); // On click, the element will become the embed! button.addEventListener("click", () => { el.classList.add("codepen"); // Add the codepen class back. window.__CPEmbed(); // Trigger the CodePen embed script to run again. }); });

All that code lives right here in this blog post, and the Embedded Pen iframe doesn’t load until you click to load it, which you might do if you’re interested in seeing that code run.

Direct Link to ArticlePermalink

The post Lazy Loaded Prefill Embeds appeared first on CSS-Tricks.

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

Black Print

Typography - Sat, 07/11/2020 - 3:00am

The remarkable story of early African American print culture; its authors, editors, journalists, printers, and publishers. From protest pamphlets to the first Black newspapers, periodicals and books.

The post Black Print appeared first on I Love Typography.

We need more inclusive web performance metrics

Css Tricks - Fri, 07/10/2020 - 4:53am

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.

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

Memorize Scroll Position Across Page Loads

Css Tricks - Thu, 07/09/2020 - 8:54am

Hakim El Hattab tweeted a really nice little UX enhancement for a static site that includes a scrollable sidebar of navigation.

https://twitter.com/hakimel/status/1262337065670316033

The trick is to throw the scroll position into localStorage right before the page is exited, and when loaded, grab that value and scroll to it. I’ll retype it from the tweet…

let sidebar = document.querySelector(".sidebar"); let top = localStorage.getItem("sidebar-scroll"); if (top !== null) { sidebar.scrollTop = parseInt(top, 10); } window.addEventListener("beforeunload", () => { localStorage.setItem("sidebar-scroll", sidebar.scrollTop); });

What is surprising is that you don’t get a flash-of-wrong-scroll-position. I wonder why? Maybe it has to do with fancy paint holding stuff browsers are doing now? Not sure.

The post Memorize Scroll Position Across Page Loads appeared first on CSS-Tricks.

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

Syndicate content
©2003 - Present Akamai Design & Development.