Web Standards

Comparing Various Ways to Hide Things in CSS

Css Tricks - Tue, 10/27/2020 - 10:45am

You would think that hiding content with CSS is a straightforward and solved problem, but there are multiple solutions, each one being unique.

Developers most commonly use display: none to hide the content on the page. Unfortunately, this way of hiding content isn’t bulletproof because now that content is now “inaccessible” to screen readers. It’s tempting to use it, but especially in cases where something is only meant to be visually hidden, don’t reach for it.

The fact is that there are many ways to “hide” things in CSS, each with their pros and cons which greatly depend on how it’s being used. We’re going to review each technique here and cap things off with a summary that helps us decide which to use and when.

How to spot differences between the techniques

To see a difference between different ways of hiding content, we must introduce some metrics. Metrics that we’ll use to compare the methods. I decided to break that down by asking questions focused on four particular areas that affect layout, performance and accessibility:

  1. Accessibility: Is the hidden content read by a screen reader?
  2. Document flow: Will the hidden element affect the document layout?
  3. Rendering: Will the hidden element’s box model be rendered?
  4. Event triggers: Does the element detect clicks or focus?

Now that we have our criteria out of the way, let’s compare the methods. Again, we’ll put everything together at the end in a way that we can use it as a reference for making decisions when hiding things in CSS.

Method 1: The display property

We kicked off this post with a caution about using display to hide content. And as we established, using it to hide an element means that the element is not generated at all. It’s in the DOM, but never actually rendered.

The element will still show in the markup, if you inspect the page you will be able to see the element. The box model will not generate nor appear on the page, which also applies to all its children.

And what’s more, if the element has any event listeners — say a click or hover — they won’t register at all. And as we’ve discussed already, all the content will be ignored by screen readers. Here, we have two visible buttons and one hidden with display: none. All three buttons have click events but only the two visible buttons will render and register the clicks.

CodePen Embed Fallback

Display is the only property that will affect image request firing. If an image tag (or parent element) has a display property set to none either through inline CSS or by selector, the image will be downloaded. On the other hand, if the image is applied with a background property, it won’t be downloaded.

This is the case because the parser hasn’t applied the CSS when an HTML document is parsed and it encounters an <img> tag. On the other hand, when we apply the image to an element with a background property, the image won’t be downloaded because the parser hasn’t applied the CSS where the image is called. This behavior is matched across all latest browsers. The only exception is IE 11, which will download images in both cases.

MetricResultIs the hidden content read by a screen reader?❌Will the hidden element affect the document layout?❌Will the hidden element’s box model be rendered?❌Does the element detect clicks or focus?❌ Method 2: The visibility property

If an element’s visibility property is set to hidden, then the element is “visually hidden.” Being “visually hidden” sounds a lot like what display: none does, but it’s incredibly different in that the element is generated and rendered, but invisible. This means that the element’s box model is present, giving it dimensions that continue to occupy space on the screen even though it doesn’t appear to be there.

Imagine you’re wearing an invisible cloak that makes you invisible to others, but you are still able to bump into things. You’re physically there, even if you’re invisible to the human eye.

But that’s where the differences between “visually hidden” and “not displayed” end. In fact, elements hidden with visibility and display behave the same in terms of accessibility and event triggers. Invisible elements are inaccessible to screen readers and won’t register events, as we see in the following demo that’s exactly the same as the last example, but merely swaps display: none with visibility: hidden.

CodePen Embed Fallback MetricResultIs the hidden content read by a screen reader?❌Will the hidden element affect the document layout?✅Will the hidden element’s box model be rendered?✅Does the element detect clicks or focus?❌ Method 3: The opacity property

The opacity property only affects the visual aspect of the element. If we set an element’s opacity to zero, the element will be fully transparent. Again, it’s a lot like visibility: hidden where we’re draping an invisible cloak on the element where it’s invisible, but still physically present.

In other words, what we have is a hollow, transparent element that acts like any other element, only it’s invisible. Sounds a lot like the visibility method, right? The difference is that a fully transparent element is still accessible to a screen reader and can register events, like clicks, as we see in the following example.

CodePen Embed Fallback MetricResultIs the hidden content read by a screen reader?✅Will the hidden element affect the document layout?✅Will the hidden element’s box model be rendered?✅Does the element detect clicks or focus?✅ Method 4: The position property

Pushing an element off-screen with absolute positioning is another way developers often hide things. Using top and left, we can push the element so far off the screen that there’s no way it will ever be seen. It’s like hiding the cookie jar outside of the house so the kids (or maybe you!) can’t find them.

“Absolute” is the key word here. If we set position to absolute, an element is taken out of the document flow which is a way of saying it no longer adheres to its natural position in the DOM. In other words, the page doesn’t reserve any space for it, which knocks the element out of order visually, positioning it to it’s nearest positioned element if there is one, or the document root if nothing else.

CodePen Embed Fallback

We take advantage of absolute positioning by taking the “hidden” element out of the document flow and offsetting it toward the top-left with values of -9999px.

.hidden { position: absolute; top: -9999px; left: -9999px; } CodePen Embed Fallback MetricEffectIs the hidden content read by a screen reader?✅Will the hidden element affect the document layout?❌Will the hidden element’s box model be rendered?✅Does the element detect clicks or focus?✅

If the hidden element contains focusable content, the page will scroll to the element when it is in focus, creating a sudden jump.

Method 5: The “visually hidden” class

So far, the position method is the closest we’ve seen to an accessibility-friendly way to hide things in CSS. But the problem with focusable content causing sudden page jumps isn’t great. Another approach to accessible hiding combines absolute positioning, the clip property and hidden overflow. Scott O’Hara blogged it back in 2017.

.visually-hidden:not(:focus):not(:active) { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; }

Let’s break that down.

We need to remove the element from the document flow. The best way to do this is by using position: absolute. This will remove the element, but we won’t push it off the screen.

.visually-hidden { position: absolute; }

We can hide the element by setting the width and height property to zero. Unfortunately, that won’t work because some screen readers will ignore elements with zero width and height. What we can do is set it to the second-lowest value, 1px. That means the content will easily overflow the space, so we also need overflow: hidden to make sure it doesn’t visually spill over.

.visually-hidden { height: 1px; overflow: hidden; position: absolute; width: 1px; }

To hide that one-pixel square, we can use the CSS clipping property. It is perfect for this situation, as it doesn’t affect screen readers. The content is there but, again, is visually hidden. The thing to note is that clip was deprecated in favor of clip-path but is still needed if we need to support older versions of Internet Explorer.

.visually-hidden { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; width: 1px; }

Another piece of the “visually hidden” class puzzle is to address smushed off-screen accessible text, an oddity that removes white-spacing between words, causing them to be read aloud like one big string of words. For example, “Welcome back home” will be read out as “Welcomebackhome.”

A simple solution to this problem is to set the white-space: nowrap:

.visually-hidden { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; }

And, finally! The last thing to consider is to allow certain element with native focus and active sites to display when they are in focus, while continuing to prevent other elements, like paragraphs, from displaying. We can use the :not pseudo-selector for that.

.visually-hidden:not(:focus):not(:active) { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } CodePen Embed Fallback MetricResultIs the hidden content read by a screen reader?✅Will the hidden element affect the document layout?❌Will the hidden element’s box model be rendered?❌Does the element detect clicks or focus?✅ Honorable mentions

There are even more methods than the five we’ve covered. For example, the text-indent property can push text off the screen like the position method:

.hidden { text-indent: -9999em; }

Unfortunately, this approach doesn’t jive with RTL writing modes. That makes it less adaptable than other solutions we’ve covered.

Another method is using transform to scale or move the element out of the way. It works the same — visually only — like opacity.

.hidden { transform: scale(0); } Let’s put everything together!

We got to a solution that will visually hide content but still be accessible. Then, should you stop using display: none? No, this is still the best way to hide an element completely (visually and accessibly).

That said, It is worth mentioning that if you want to achieve an opposite result — hide something from the screen reader, the aria-hidden="true" attribute will hide the content from screen readers, but not visually.

With that, here is a complete table that compares all of the approaches. Use it to guide your decisions on how to hide content next time you find yourself in that situation.

MetricDisplayVisibilityOpacityPositionAccessible WayIs the hidden content read by a screen reader?❌❌✅✅✅Will the hidden element affect the document layout?❌✅✅❌❌Will the hidden element’s box model be rendered?❌✅✅✅❌Does the element detect clicks or focus?❌❌✅✅✅

The post Comparing Various Ways to Hide Things in CSS appeared first on CSS-Tricks.

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

Anima 4.0: Go Straight From Design to React in the Design Handoff

Css Tricks - Tue, 10/27/2020 - 4:27am

Imagine this scenario: You get an email from the design team. It contains a link to a high-fidelity prototype of a React app they want you to build. You click the link and get ready to inspect the work only to find… the components have already been built.

Huh?

It might sound like a dream or wishful thinking, but that’s exactly what Anima 4.0 does. For years, Anima has worked to streamline the handoff between design and development, and with it’s latest update, designers are brought fully into the fold by turning designs into developer-friendly code.

Let’s repeat that again, but more specifically: Anima 4.0 lets you cherry-pick elements straight from a design and get fully written React components that just work.

The easiest design handoff ever

Anima isn’t your typical design-to-development workflow. It actually feels a little inaccurate to say that it facilitates handoffs because development is part of the process all along.

Consider what’s involved in a design handoff. Sure, it varies by organization, but they generally flow something like this:

  • Design creates high-fidelity mockups.
  • Design creates a package of the work, possibly including assets, like images and fonts.
  • Design and development meet up and talk things out, possibly with an interactive prototype.
  • Development gets started.
  • Development demos the work.
  • Design requests changes.
  • Development makes those changes.
  • And on and on…

With Anima 4.0, that process is more like this:

  • Design creates code-based prototypes.
  • Development works alongside, with the ability to reference prototypes, grab assets, generate code, and test things out.
Development is an integrated component of the design process, where code is always whether you’re in the prototype or the design application.

So, what we have is less of a handoff and more of a productive and collaborative process that saves boatloads of time… and frustration to boot.

No more “How does this thing work?”

That’s probably the question I ask the most with any design handoff. Front-enders have to be aware of so many things and that often leads to lengthy meetings and numerous emails about how things are supposed to work.

  • Where does this link to?
  • Does this have an active state?
  • Will this image be SVG?
  • …you know how it goes

That’s where Anima shines. The deliverable is not just a flat design, but a fully interactive prototype. All of the links, states, assets, and anything else you can think of is right there for you to view and interact with, including animations and effects.

Oh, and if your design is responsive (which, of course, it is), it’s easy as cake to see how it behaves at any breakpoint, whether you’re using the integrated browser in the design application or in the Anima prototype.

The design can be previewed in a real browser at any time directly in the design app.

Getting the responsiveness of a design down pat is probably one of the more time-consuming parts of a project. I’ve had so many back-and-forth discussions with designers that would have never happened if it was possible to test the design in a real browser during design in the design tooling that designers are probably already using, including Sketch, Figma and Adobe XD. And because Anima generates all the code, that would have saved a lot of my time trying to get the breakpoints just right. It would have also saved the designers time without having to document that behavior and answer all my questions.

How cool is it that designers can test their designs in an actual browser that’s built into their design app?! No more “That’s not how it was designed!”

Not only do you have a prototype that realistically simulates a live site, but you get all the code you need! And no, this isn’t like the HTML and CSS generators you’ve probably seen in the past. Anima outputs extremely clean code, complete with semantic HTML elements and modern CSS features. Here’s the CSS I got from a quick design of a hero component I threw together:

@import url("https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"); .hero { background-color: transparent; flex-shrink: 0; height: 1037px; position: relative; width: 505px; } .hero-container { background-color: var(--royal-blue); height: 1024px; left: 0px; position: absolute; top: 0px; width: 505px; } .shape-circle { background-color: transparent; height: 444px; left: 283px; position: absolute; top: 593px; width: 222px; } .shape-dots { background-color: transparent; height: 646px; left: 43px; position: absolute; top: 189px; width: 418px; } .shape-triangle { background-color: transparent; height: 332px; left: 0px; position: absolute; top: 79px; width: 269px; } .video { background-color: transparent; height: 294px; left: 43px; overflow: hidden; position: absolute; top: 278px; width: 418px; } :root { --royal-blue: rgba(67,83,255,1.0); }

Lots of precise numbers in there that normally would have taken some time-consuming guesswork. And those are class names and custom properties I can actually pronounce! Will I change any of that code? Maybe! But at least I was part of the process all along, and have a solid head start that I would have otherwise spent time writing myself.

But, the real gem here is that Anima 4.0 goes where no other platform has gone because it can…

Turn anything into a functional React component

All it took was a single click and here’s what I got:

import React from "react"; function App(props) { return ( <div className={`hero ${props.className || ""}`}> <div className="hero-container"></div> <img className="shape-circle" src="https://anima-uploads.s3.amazonaws.com/projects/5f8e220bdff56f27ee5b7cc7/releases/5f9082de53033dac763b4b6c/img/desktop-hd-learn-path-2-DC8E0494-121C-40B1-8AE1-3C8BEAC833A7.png" /> <img className="shape-triangle" src="https://anima-uploads.s3.amazonaws.com/projects/5f8e220bdff56f27ee5b7cc7/releases/5f9082de53033dac763b4b6c/img/desktop-hd-home-triangle2x-BA81FE1D-AE06-47A2-91D5-20EC51D5F0F8.png" /> <img className="shape-dots" src="https://anima-uploads.s3.amazonaws.com/projects/5f8e220bdff56f27ee5b7cc7/releases/5f9082de53033dac763b4b6c/img/desktop-hd-home-rectangle2x-4EFFE4A8-CAD1-47C7-A175-D3256F2E5124.png" /> <div className="video"> <iframe style="border: 0; pointer-events: auto;" id="ytplayer" type="text/html" width="100%" height="100%" src="https://www.youtube.com/embed/rk71kS4cY7E?rel=0" frameborder="0" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen" ></iframe> </div> </div> ); } export default App;

This is real — and brand new in Anima 4.0! And I can do this with any element in the Anima interface. Select an element, mark it as a component, then generate the code.

You can expect the same for Vue and Angular in future releases.

Why this is a big deal

Perhaps it’s obvious by now, but I see tons of benefits from where I sit as a front-end developer. Getting HTML and CSS is great, but having a tool like this that integrates with modern frameworks and code practices is more than impressive — it’s a game-changer. There’s a lot less context switching and time spent on things that I’d rather spend doing better work (or getting started on the next project)!

Like many of you, I straddle the line between design and development and see how this fills a lot of the gaps on the design side of things as well. I can’t get over the in-app browser previews. All of the time spent design QA’ing responsive breakpoints instantly opens up when that stuff can be done at the point of design — not to mention the time saved with the code it generates.

Here’s a quick video of moving from Adobe XD to a real rendered React components in the browser:

Anima 4.0 is available… today

As in, it literally shipped today, October 27. In fact, there’s a virtual party happening and you’re invited. I’m told it’s going to be an epic geeky event with great folks, demos, and even gifts. Hope to see you there!

Get Anima 4.0

The post Anima 4.0: Go Straight From Design to React in the Design Handoff appeared first on CSS-Tricks.

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

Thidrekssaga II: Wieland the Smith

QuirksBlog - Tue, 10/27/2020 - 3:35am

Just now I published part II of the Thidrekssaga: Wieland the Smith.

Here we are told about Wieland the Smith and why and how he forged the sword Mimung that will be carried by his son Witig and will play an important role in the saga. It is so hard and sharp that no armour can stand against it, as will be proved by an impressive casualty list, starting with a competing smith. Even Dietrich himself will have to contend against it.

Note that Mimung is not a magic sword — in fact, the saga tells us exactly how it is forged, and the tale even makes chemical sense. No ladies in lakes here, or even dwarves, although Wieland was apprenticed to dwarves and might have learned his art there.

Enjoy.

Core Web Vital Tooling

Css Tricks - Mon, 10/26/2020 - 9:50am

I still think the Google-devised Core Web Vitals are smart. When I first got into caring about performance, it was all: reduce requests! cache things! Make stuff smaller! And while those are all very related to web performance, they are abstractly related. Actual web performance to users are things like how long did I have to wait to see the content on the page? How long until I can actually interact with the page, like type in a form or click a link? Did things obnoxiously jump around while I was trying to do something? That’s why Core Web Vitals are smart: they measure those things.

The Lighthouse Tab in Chrome DevTools has them now:

They are nice to keep an eye on, because remember, aside those numbers having a direct benefit for your users once they get to your site, they might affect users getting to your site at all. Web Core Vitals are factoring into SEO and for the new carousel requirements that were previously reserved only for AMP pages.

Tracking these numbers on one-off audits is useful, but more useful is watching them over time to protect yourself from slipping. Performance tooling like Calibre covers them. New Relic has got it. SpeedCurve tracks them.

Cumulative Layout Shift (CLS) is a tricky one. That’s the one where, say, the site has an advertisement at the top of an article. The request for that ad is asynchronous, so there is a good chance the ad comes in late and pushes the content of the article down. That’s not just annoying, but a real ding to performance metrics and, ultimately, SEO.

Nic Jansma’s “Cumulative Layout Shift in Practice” offers deep dive.

CLS isn’t just “does page do it or not?” There is a score, as that illustration above points out. I’d say 0 is a good goal as there is no version of CLS that is good for anybody. There is lots of nuance to this, like tracking it “synthetically” (e.g. in a headless browser, especially for performance tooling) and with real users on your real site (which is called RUM, or Real User Metrics). Both are useful.

If you’ve got CLS that you need to fight, that can be tricky. SpeedCurve has some new tooling that helps:

For each layout shift, we show you the filmstrip frame right before and right after the shift. We then draw a red box around the elements that moved, highlighting exactly which elements caused the shift. The Layout Shift Score for each shift also helps you understand the impact of that shift and how it adds to the cumulative score.

That would make it pretty easy to root out and fix, I’d hope. Particularly the tricky ones. I didn’t know this, but CLS can be caused by far more subtle things which Mark Zeman points out in the post. For example:

  • An image carousel that only moves horizontally can trigger CLS. That feels like a bummer as that’s what they are supposed to do, but apparently, you can trick it by moving carousels only with CSS transform.
  • If you have a very large area, that’s extra risky to move. If it moves just a smidge, it will affect CLS by a lot.
  • Flash of Unstyled Text (FOUT) is a cause of CLS. Even though that’s good for performance for other reasons! Catch 22! It’s a good excuse to reach for perfect font fallbacks.

Tricky, yet important stuff. I really need to get performance tests into my CI/CD, which will really help with this. Feels more and more like web performance is a full-on career subgenre of web development. Front-end web developers really need to understand this stuff and help to some degree, but we’ve already got so much to do.

The post Core Web Vital Tooling appeared first on CSS-Tricks.

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

WordPress and Jamstack

Css Tricks - Mon, 10/26/2020 - 5:11am

I recently moderated a panel at Netlify’s virtual Jamstack Conf that included Netlify CEO Matt Biilman and Automattic founder Matt Mullenweg. The whole thing was built up — at least to some — as a “Jamstack vs. WordPress” showdown.

I have lots of thoughts of my own on this and think I’m more useful as a pundit than a moderator. This is one of my favorite conversations in tech right now! So allow me to blog.

Disclosure: both Automattic and Netlify are active sponsors of this site. I have production sites that use both, and honestly, I’m a fan of both, which is an overarching point I’ll try to make. I also happen to be writing and publishing this on a WordPress site.

History
  1. Richard MacManus published “WordPress Co-Founder Matt Mullenweg Is Not a Fan of JAMstack” with quotes from an email conversation between them a line from Matt saying, “JAMstack is a regression for the vast majority of the people adopting it.”
  2. Matt Biilmann published a response “On Mullenweg and the Jamstack – Regression or Future?” with a whole section titled “The end of the WordPress era.”
  3. People chimed in along the way. Netlify board member Ohad Eder-Pressman wrote an open letter. Sarah Gooding rounded up some of the activity on WP Tavern (which is owned by Matt Mullenweg). I chimed in as well.
  4. Matt Mullenweg clarified remarks with some new zingers.

The debate was on October 6th at Jamstack Conf Virtual 2020. There is no public video of it (sorry).

The Stack

Comparing Jamstack to WordPress is a bit weird. What is comparable is the fact that they are both roads you might travel when building a website. Much of this post will keep that in mind and compare the two that way. Why they aren’t directly comparable is because:

  • Jamstack is a loose descriptor of an architectural philosophy that encourages static files on CDNs and JavaScript-accessed services for any dynamic needs.
  • WordPress is a CMS on the LAMP stack.

Those things are not apples to apples.

If we stick just with the stack for a moment, the comparison would be between:

  • Static Hosting + Services
  • LAMP

An example of Static + Services is using Netlify for hosting (which is static) and using services to do anything dynamic you need to do. Maybe you use Netlify’s own forms and auth functionality and Hasura for data storage.

On a LAMP stack, you have MySQL to store data in, so you aren’t reaching for an outside service there. You also have PHP available. So with those (in addition to open-source software), you have what you need for auth. It doesn’t mean that you never reach for services; you just do so less often as you have more technology at your fingertips from the server you already have.

Jamstack: Static Hosting as the hub, reaching out to services for everything else.

LAMP: Server that does a bunch of work as the hub, reaching out to a few services if needed.

Matt B. called the LAMP stack a “monolith.” Matt M. objected to that term and called it an “integrated approach.” I’m not a computer scientist, but I could see this going either way. Here’s Wikipedia:

[…] a monolithic application describes a single-tiered software application in which the user interface and data access code are combined into a single program.

Defined that way, yes, WordPress does appear to be a monolith, and yet the Wikipedia article continues:

[…] a monolithic application describes a software application that is designed without modularity.

Seen that way, appears to disqualify WordPress as a monolith. WordPress’ hook and plugin architecture is modular. &#x1f937;‍♂️

It would be interesting to hear these two guys dig into the nuance there, but the software is what it is. A self-hosted WordPress site runs on a server with a full stack of technology available to it. It makes sense to ask as much of that server as you can (i.e. integrated). In a Jamstack approach, the server is abstracted from you. Everything else you need to do is split into different services (i.e. not integrated).

The WordPress approach, doesn’t mean that you never reach for outside services. In both stacks, you’d likely use something like Stripe for eCommerce APIs. You might reach for something like Cloudinary for robust media storage and serving. Even WordPress’ Jetpack service (which I use and like) brings a lot of power to a self-hosted WordPress site by behaving like a third-party service and moving things like asset-hosting and search technology off your own servers by moving them over to cloud servers. Both stacks are conglomerations of technologies.

Neither stack is any more “house of cards” or prone than the other. All websites can have that “only as strong as its weakest link” metaphor apply to them. If a WordPress plugin ships a borked version or somehow is corrupted on upload, it may screw up my site until I fix it. If my API keys become invalid for my serverless database, my Jamstack site might be hosed until I fix it. If Stripe is down, I’m not selling any products on any kind of site until they are back up.

A missing semicolon can sink any site. Pricing

WordPress.com has a free plan, and that’s absolutely a place you can build a site. (I have several.) But you don’t really have developer-style access to it until you’re on the business plan at $25 per month. Self-hosted WordPress itself is open-source and free, but you’re not going to find a place to spin up a self-hosted WordPress site for free. It starts cheap and scales up. You need LAMP hosting to run WordPress. Here’s a look around at fairly inexpensive hosting plans:

There is money involved right off the bat.

Starting free is much more common with Jamstack, then you incur costs at different points. Jamstack being newer, it feels like a market that’s still figuring itself out.

  • Vercel is free until you need team members or features like password protected sites. A single password-protected site is $150/month. You can toss basic auth on any server with Apache for no additional cost.
  • Netlify is very similar, unlocking features on higher plans, and offering ala-carte per-site features, like analytics ($9/month) and auth (5,000 active users is $99/month).
  • AWS Amplify starts free, but like everything on AWS, your usage is metered on lots of levels, like build minutes, storage, and bandwidth. They have an example calculation of a web app has 10,000 daily active users and is updated two times per month, which costs $65.98/month.
  • Azure Static Web Apps hasn’t released pricing yet, but will almost certainly have a free tier or free usage or some kind.

All of this is a good reminder that Netlify isn’t the only one in the Jamstack game. Jamstack just means static hosting plus services.

You can’t make blanket statements like Jamstack is cheaper. It’s far too dependent on the site’s usage and needs. With high usage and a bunch of premium services, Jamstack (much like Serverless in general) can get super expensive. Jamstack says their enterprise pricing starts at $3,000/month, and while you get things like auth, forms, and media handling, you don’t get a CMS or any data storage, that is likely to kick you up much higher.

While this WordPress site isn’t enterprise, I can tell you it requires a server in the vicinity of a $1,000/month, and that assumes Cloudflare is in front of it to help reduce bandwidth directly to the host and Jetpack handling things like media hosting and search functionality. Mailchimp sends our newsletter. Wufoo powers our forms. We also have paid plugins, like Advanced Custom Fields Pro and a few WooCommerce add-ons. That’s not all of it. It’s probably a few thousand per month, all told. This isn’t unique to any integrated approach, but helps illustrate that the cost of a WordPress site can be quite high as well. They don’t publish prices (a common enterprise tactic), but Automattic’s own WordPress VIP hosting service surely starts at mid-4-figures before you start adding third-party stuff.

Bottom line: there is no sea change in pricing happening here.

Performance

80% of web performance is a front-end concern.

That’s a true story, but it’s also built on the foundation of the server (accounting for the first 20%). The speediest front-end in the world doesn’t feel speedy at all if the first request back from the server takes multiple seconds. You’ve gotta make sure that first request is smoking fast if you want a fast site.

The first rectangle is the first server response, and the second is the entire front-end. Even with a fast front end, it can’t save you from a slow back end.

You know what’s super fast? Global CDNs serving static files. That’s what you want to make happen on any website, regardless of the stack. While that’s the foundation of Jamstack (static CDN-backed hosting), it doesn’t mean WordPress can’t do it.

You take an index.html file with static content, put that on Netlify, and it’s gonna be smoking fast. Maybe your static site generator makes that file (which, it’s worth pointing out, could very well get content from WordPress). There is something very nice about the robustness and steady foundation of that.

By default, WordPress isn’t making static files that are cachable on a global CDN. WordPress responds to requests from a single origin, runs PHP, which asks the database for stuff, before a response is assembled, and then, finally, the page is returned. That can be pretty fast, but it’s far less sturdy than a static file on a global CDN and it’s far easier to overwhelm with requests.

WordPress hosts know this, and they try to solve the problem at the hosting level. Just look at WP Engine’s approach. Without you doing anything, they use a page cache so that the site can essentially return a static asset rather than needing to run PHP or hit a database. They employ all sorts of other caching as well, including partnering with Cloudflare to do the best possible caching. As I’m writing this, my shoptalkshow.com site literally went down. I wrote to the host, Flywheel, to see what was up. Turns out that when I went in there to turn on a staging site, I flipped a wrong switch and turned off their caching. The site couldn’t handle the traffic and just died. Flipping the caching switch back on instantly solved it. I didn’t have Cloudflare in front of the site, but I should have.

Cloudflare is part of the magic sauce of making WordPress fast. Just putting it in front of your self-hosted WordPress site is going to do a ton of work in making it fast and reliable. One of the missing pieces has been great caching of the HTML itself, which they literally dealt with this month and now that can be cached as well. There is kind of a funny irony in that caching WordPress means caching requests as static HTML and static assets, and serving them from a global CDN, which is essentially what Jamstack is at the end of the day.

Matt M. mentioned that WordPress.com employs global CDNs that kick in at certain levels of traffic. I’m not sure if that’s Cloudflare or not, but I wouldn’t doubt it.

With Cloudflare in front of a WordPress site, I see the same first-response numbers as I do on Netlify sites without Cloudflare (because the do not recommend using Cloudflare in front of Netlify-hosted sites). That’s mid-2-digit millisecond numbers, which is very, very good.

First request on WordPress site css-tricks.com, hosted by Flywheel with Cloudflare in front. Very fast. First request on my Jamstack site, conferences.css-tricks.com, hosted by Netlify. Very fast.

From that foundation, any discussion about performance becomes front-end specific. Front-end tactics for speed are the same no matter what the server, hosting, or CMS situation is on the back end.

Security

There are far more stories about WordPress sites getting hacked than Jamstack sites. But is it fair to say that WordPress is less secure? WordPress is going on a couple of decades of history and has a couple orders of magnitude more sites built on it than Jamstack does. Security aside, you’re going to get more stories from WordPress with those numbers.

Matt M brought up that whitehouse.gov is on WordPress, which is obviously a site that needs the highest levels of security. It’s not that WordPress itself is insecure software. It’s what you do with it. Do you have insecure passwords? That’s insecure no matter what platform you’re using. Is the server itself insecure via file permissions or access levels? That’s not exactly the software’s fault, but you may be in that position because of the software. Are you running the latest version of WordPress? Usage is fragmented, at best, and the older the version, the less secure it’s going to be. Tricky.

It may be more interesting to think about security vectors. That is, at what points it is possible to get hacked. If you have a static file sitting on static hosting, I think it’s safe to say there are fairly few attack vectors. But still, there are some:

  • Your hosting account could be hacked
  • Your Git repo could be hacked
  • Your Cloudflare account could be hacked
  • Your domain name could be stolen (it happens)

That’s all true of a WordPress site, too, only there are additional attack vectors like:

  • Server-side code: XSS, bad plugins, remote execution, etc.
  • Database vulnerabilities
  • Running an older, outdated version of WordPress
  • The login system is right on the site itself, e.g. bad guys can hammer /wp-login.php

I think it’s fair to say there are more attack vectors on a WordPress site, but there are plenty of vectors on any site. The hosting account of any site is a big vector. Anyting that sits in the DNS chain. Any third-party services with logins. Anything with an API key.

Personal experience: this site is on WordPress and has never been hacked, but not for lack of trying. I do feel like I need to think more about security on my WordPress sites than my sites that are only built from static site generators.

Scaling

Scaling either approach costs money. This WordPress site isn’t massively scaled, but does require some decent scaling up from entry-level server requirements. I serve all traffic through Cloudflare, so a peak at the last 30 days tells me I serve 5 TB of bandwidth a month.

On a Netlify Business plan (600 GB of traffic for $99, then $20 per additional 100 GB) that math works out to $979. Remember when I said this site requires about a server that costs about $1,000/month? I wrote that before I ran these numbers, so I was super close (go me). Jamstack versus WordPress at the scale of this site is pretty neck-and-neck. All hosts are going to charge for bandwidth and have caps with overage charges. Amplify charges $0.15/GB over a 15 GB monthly cap. Flywheel (my WordPress host) charges based on a monthly visitor cap and, over that, it’s $1 per 1000.

The story with WordPress scaling is:

  • Use a host that can handle it and that has their own proven caching strategy.
  • CDN everything (which usually means putting Cloudflare in front of it).
  • Ultimately, you’re going to pay for it.

The story with Jamstack scaling is:

  • The host and services are built to scale.
  • You have to think about scaling less in terms of can this service handle this, or do I have to move?
  • You have to think about scaling more in terms of the fact that every aspect of every service will have pricing you need to keep an eye on.
  • Ultimately, you’re going to pay for it.

I’ve had to move around a bit with my WordPress hosting, finding hosts that are in-line with the current needs of the site. Moving a WordPress site is non-trivial, but it’s far easier than moving to another CMS. For example, if you build a Jamstack site on a headless CMS that becomes too pricey, the cost of moving is a bigger job than switching hosts.

I like what Dave Rupert wrote the other day (in a Slack conversation) about comparing performance between the two:

Jamstack: Use whatever thing to build your thing, there’s addons to help you, and use our thing to deploy it out to a CDN so it won’t fall over.

WordPress: Use our thing to build your thing, there’s addons to help you, and you have to use certain hosts to get it to not fall over.

There are other kinds of “scaling” as well. I think of something like number of users. That’s something that all sorts of services use for pricing tiers, which is an understandable metric. But that’s free in WordPress. You can have as many users with as many nuanced permissions as you like. That’s just the CMS, so adding on other services might still charge you by the head. Vercel or Netlify charge you by the head for team accounts. Contentful (a popular headless CMS) starts at $489/month for teams. Even GitHub’s Team tier is $4 per user if you need anything the free account can’t do.

Splitting the Front and Back

This is one of the big things that gets people excited about building with Jamstack. If all of my site’s functionality and content are behind APIs, that frees up the front end to build however it wants to.

  • Wanna build an all-static site? OK, hit that API during the build process and do that.
  • Wanna build a client-rendered site with React or Vue or whatever? Fine, hit the API client-side.
  • Wanna split the middle, pre-rendering some, client-rendering some, and server-rendering some? Cool, it’s an API, you can hit it however you want.

That flexibility is neat on green-field builds, but people are just as excited about theoretical future flexibility. If all functionality and content is API-driven, you’ve entirely split the front and back, meaning you can change either in the future with more flexibility.

  • As long as your APIs keep spitting out what the front end expects, you can re-architect the back end without troubling the front end.
  • As long as you’re getting the data you need, you can re-architect the front end without troubling the back end.

This kind of split feels “future safe” for sites at a certain size and scale. I can’t quite put my finger on what those scale numbers are, but they are there.

If you’ve ever done any major site re-architecture just to accommodate one side or the other, moving to a system where you’ve split the back end and front surely feels like a smart move.

Once we’ve split, as long as the expectations are maintained, back (B) and front (F) are free to evolve independently.

You can split a WordPress site (we’ll get to that in the “Using Both” section), but by default, WordPress is very much an integrated approach where the front end is built from themes in PHP using very WordPress-specific APIs. Not split at all.

Developer Experience

Jamstack has done a good job of heavily prioritizing developer experience (DX). I’ve heard someone call it “a local optimum,” meaning Jamstack is designed around local development (and local developer) experience.

  • You’re expected to work locally. You work in your own comfortable (local, fast, customized) development environment.
  • Git is a first-class citizen. You push to your production branch (e.g. master or main), then your build process runs, and your site is deployed. You even get a preview URL of what the production site will be for every pull request, which is an impressively great feature.
  • Use whatever tooling you like. You wanna pre-build a site in Hugo? Go for it. You learned create-react-app in school? Use that. Wanna experiment with the cool new framework de jour? Have at it. There is a lot of freedom to build however you want, leveraging the fact that you can run a build and deploy whatever folder in your repo you want.
  • What you don’t have to do is important, too. You don’t have to deal with HTTPS, you don’t have to deal with caching, you don’t have to worry about file permissions, you don’t have to configure a CDN. Even advanced developers appreciate having to do less.

It’s not that WordPress doesn’t consider developer experience (for example, they have a CLI and it can do helpful things, like scaffold blocks), but the DX doesn’t feel as to-the-core of the project to me.

  • Running WordPress locally is tricky, requiring you to run a (X)AMP stack somehow, which involves notoriously finicky third-party software. Thank god for Local by Flywheel. There is some guidance but it doesn’t feel like a priority.
  • What should go in Git? To this day, I don’t really know, but I’ve largely settled on the entire /wp-content folder. It feels weird to me there is no guidance or obvious best practices.
  • You’re totally on your own for deployment. Even WordPress-specific hosts don’t really nail it here. It’s largely just: here’s your SFTP credentials.
  • Even if you have a nice local development and deployment pipeline set up (I’m happy with mine), that doesn’t really help deal with moving the database around, so you’re on own your own there as well.

These are all solvable things, and the WordPress community is so big that you’ll find plenty of information on it, but I think it’s fair to say that WordPress doesn’t have DX down to the core. It’s a little wild-west-y even after all these years.

In fact, I’ve found that because the encouragement of a healthy local development environment is so sidelined, a lot of people just don’t have one at all. This is anecdotal, but now twice is as many years have I found myself involved in other people’s sites that work entirely production-only. That would be one thing if they were very simple sites with largely default behavior, but these have been anything but. They’re very complicated (much more so than this site) involving public user logins, paid memberships and permissions, page builders, custom shortcodes, custom CSS, and just a heck of a lot of moving parts. It scared me to death. I didn’t want to touch anything. They were live-editing PHP to make things work — cowboy coding, as people jokingly call that. One syntax error and the site is hosed, maybe even the very page you’re looking at.

The fact that WordPress powers such a huge swath of the web without particularly good DX is very interesting. There is no Jamstack without DX. It’s an entirely developer-focused thing. With WordPress, there probably isn’t a developer at all on most sites. It’s installed (or just activated, in the case of WordPress.com) and the site owner takes it from there. The site owner is like a developer in that they have lots of power, but perhaps doesn’t write any code at all.

To that end, I’d say WordPress has far more focus on UX than DX, which is a huge part of all this…

CMS and End User UX

WordPress is a damn fine CMS. Even if you don’t like it, there are a hell of a lot of people that do, and the numbers speak for themselves. What you get, when you decide to build a site with WordPress, is a heaping helping of ability to build just about any kind of site you want. It’s unlikely that you’ll have that oops, painted myself into a corner here situation with WordPress.

That’s a big deal. Jenn put her finger on this, noting that the people who use WordPress are a bigger story than a developer’s needs.

WordPress can do an absolute ton of things:

  • Blog (or be any type of content-driven CMS-style site)…
    • With content previews, which is possible-but-tricky on Jamstack
  • Deal with users/permissions…
  • eCommerce
  • Process forms
  • Handle plugins to the moon and back

Jamstack can absolutely do all these things too, but now it is Jamstack that is in Wild West territory. When you look at tutorials about how to store data, they often involve explaining how to write individual CRUD functions for a cloud database. That’s down to the metal stuff which can be very powerful, but it’s a far cry from clicking a few buttons, which is what WordPress feels like a lot of the time.

I bet I could probably cobble together a basic Jamstack eCommerce setup with Stripe APIs, which is very cool. But then I’d get nervous when I need to start thinking about inventory management, shipping zones, product variations, and who knows what else that gets complicated in eCommerce-land, making me wish I had something super robust that did it all for me.

Sometimes, we developers are building sites just for us (I do more than my fair share of that), but I’d say developers are mostly building sites for other people. So the most important question is: am I building something that is empowering for the people I’m building it for?

You can pull off a good site manager experience no matter what, but WordPress has surely proven that it delivers in that department without asking terribly much in terms of custom development.

Jamstack has some tricks that I wish I would pull off on WordPress, though. Here’s a big one for me: user-submitted content and updates. I literally have three websites now that benefit from this. A site about conferences, a site about serverless, and an upcoming site about coding fonts. WordPress could have absolutely done a great job at all three of those sites. But, what I really want is for people to be able to update and submit content in a way that I can be like: Yep, looks good, merge. By having gone with a Jamstack approach, the content is in public GitHub repos, and anyone can participate.

I think that’s super great. It doesn’t even necessarily require someone from the public knowing or understanding Git or GitHub, as Netlify CMS has this concept of Open Authoring, which keeps the whole contribution experience in the browser with UI for the editing.

Using Both

This is a big one that I see brought up a lot. Even Netlify themselves say “There is no Versus.”

Here’s the deal:

  • The “A” in “Jam” means APIs. Use APIs to build your site either at build time or client-side.
  • WordPress sites, by default, have a REST API (and can have a GraphQL API as well).
  • So, hit that API for CMS data on your Jamstack site.

Yep, totally. This works and people do it. I think it’s pretty cool.

But…

  • Running a WordPress site somewhere in addition to your Jamstack site means… you’re running a WordPress site in addition to your Jamstack site. There is cost and technical debt to that.
  • You often aren’t getting all the value of WordPress. Hitting an API for data might be all you need, but this is a super, very different approach to building a site than building a WordPress theme. You’re getting none of the other value of WordPress. I think of situations like this: you find a neat plugin that adds a fancy Gutenberg block to your site. That’ll “just work” on a WordPress site, but it likely has some special front-end behavior that won’t work if all you’re doing is sucking the HTML from an API. It probably enqueues some additional scripts and styles that you’ll be on your own to figure out how to incorporate where your front-end is hosted, and on your own to maintain updates.

Here’s some players that all have a unique approach to “using both”:

  • Frontity: A React framework for WordPress. You run it with a Node server behind it, in addition to your WordPress site. The Node server renders the React into HTML, so you get server-side rendering for all the pages, but you’re also still building an SPA.
  • WP2Static: A WordPress plugin that builds a static version of your site and can auto-deploy it when changes are made.
  • Strattic: They host the dynamic WordPress site for you (which they refer to as “staging”) and you work with WordPress normally there. Then you choose to deploy, and they also host a static version of your site for you.
  • Shifter: Shifter hosts the WordPress site for you. You have two options: 1) run it headlessly (so you’re just hitting the API, REST or GraphQL, for data) or 2) run it statically (so when you have everything in WordPress where you want it, you deploy it, which creates a static version of your site, which they also host, or you can push it elsewhere e.g. Netlify).

There are loads of other ways to integrate both. Here’s our own Geoff and Sarah talking about using WordPress and Jamstack together by using Vue/Nuxt with the REST API and hosting on Netlify.

Using Neither

Just in case this isn’t clear, there are absolutely loads of ways to build websites. If you’re building a Ruby on Rails site, that’s not Jamstack or WordPress. You could argue it’s more like a WordPress site in that it requires a server and you’ll be using that server to do as much as you can. You could also argue it’s more like Jamstack in that, even though it’s not static hosting, it encourages using APIs and piecing together services.

The web is a big place, gang, and this isn’t a zero-sum game. I fully expect WordPress to continue to grow and Jamstack to continue to grow because the web itself is growing. Even if we’re only considering the percentage of market share, I’d still bet that both will grow, pushing whatever else into smaller slices.

Choosing

I’m not even going to go here. Not because I’m avoiding playing favorites, but because it isn’t necessary. I don’t see developers out there biting their fingernails trying to decide between a WordPress or Jamstack approach to building a website. We’re at the point where the technologies are well-understood enough that the process goes like:

  1. Put adult pants on
  2. Evaluate needs and outcomes
  3. Pick technologies

The post WordPress and Jamstack appeared first on CSS-Tricks.

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

Linkbait 47

QuirksBlog - Mon, 10/26/2020 - 4:18am

Insert funny tagline here.

  • The State of CSS 2020 survey is running, Please take it! It’s important for fifguring out where CSS should go next, and what people actually know. Slight disadvantage: you have to register. I’m not totally sure what to make of that, and hope that future versions leave it out, but in the end I did register because I think the survey is important enough.
  • Excellent question: What does 100% mean in CSS? I always tell my CSS students to ask that question, and sometimes the answer is non-obvious. This page treats a few of the simpler use cases, as well as margin and padding, which are not so much complicated but rather counter-intuitive.
  • Rachel Andrew explains CSS masking. Does more need to be said? No.
  • Lea Verou invents a way to unset CSS custom properties. This can be very useful for toggling page-wide or component-wide states. The trick? Simply making the custom property’s value a whitespace. It’s allowed, but doesn’t have any meaning, ergo, the property is unset.
  • Nicholas Zakas explains JavaScript promises (in a multi-part series) by writing a promises tool, which requires you to fully understand the underlying technology.
    I mainly include this for myself; I need to fully understand promises as well, and this series is just what I need.
  • Coil, the most interesting web monetisation project of the moment, releases its developer site. Unfortunately, creating a Coil account is not a smooth process, but this page helps. Also gives information about the web monetization standard. Still fairly bare-bones, but hey, it’s been out there only for a couple of week. Let’s give it time to grow.
  • Oh, and TechDirt decided to give Coil a spin and see what happens.
  • Another money-related system is Libra, though it is not specifically for the web. Instead, as far as I can glean from the fairly bare-bones information, it works by storing money on your phone, like systems such as mPesa do. Also, it has a new programming language (why?) and buzzwords.
    Not to disparage them immediately, but a clearer idea how how the system works for users in four paragraphs would have been useful.
  • And privacy: The Global Privacy Control specification and its implementations are coming online. Not yet in the major browsers, but once it works you should be able to have control over what you do and don’t tell websites. Unfortunately Chrome will never implement it; the idea is to much at odds with Google’s interest as an ad supplier.
  • An important piece by Benedict Evans: The end of the American internet. With TikTok, Americans have to face a foreign social network being used massively in their country for the first time. The American internet is over. Let’s see if it adjusts their preconceptions. (My guess: no.)
  • The Mozilla Browser Compatibility Report 2020 is here, focusing on how web developers see browser compatibility. The two top pain points are IE (duh) and layout and style, which is a rather broad category but ties in with my idea that layout is badly understood, though I'm still not sure why. Fortunately the report contains many examples.
  • A Brief Totally Accurate History Of Programming Languages. As it says on the tin.
  • What did the Roman emperors look like? We have quite decent portraits of especially the earlier ones, and the Romans believed in realistic portrayal: if you have a wart on your nose your portrait has a wart on its nose. Now this has been taken one step further by adding some modern algorithms to the portraits, stirring in some ancient written sources, and the result is life-like portraits in modern CGI. No proof that these are 100% correct (skin colour is rarely described explicitly, for inatance, and cannot be inferred from marble busts), but it’s still fascinating to see.
  • Have a tip for the next Linkbait? Or a comment on this one? Let me know (or here or here).

Creating CSS Shapes with Emoji

Css Tricks - Fri, 10/23/2020 - 12:36pm

CSS Shapes is a standard that lets us create geometric shapes over floated elements that cause the inline contents — usually text — around those elements to wrap along the specified shapes.

Such a shaped flow of text looks good in editorial designs or designs that work with text-heavy contents to add some visual relief from the chunks of text.

Here’s an example of CSS Shape in use:

CodePen Embed Fallback

The shape-outside property specifies the shape of a float area using either one of the basic shape functions — circle(), ellipse(), polygon() or inset() — or an image, like this:

CodePen Embed Fallback

Inline content wraps along the right side of a left-floated element, and the left side of a right-floated element.

In this post, we’ll use the concept of CSS Shapes with emoji to create interesting text-wrapping effects. Images are rectangles. Many of the shapes we draw in CSS are also boxy or at least limited to standard shapes. Emoji, on the other hand, offers neat opportunities to break out of the box!

Here’s how we’ll do it: We’ll first create an image out of an emoji, and then float it and apply a CSS Shape to it.

I’ve already covered multiple ways to convert emojis to images in this post on creative background patterns. In that I said I wasn’t able to figure out how to use SVG <text> to do the conversion, but I’ve figured it out now and will show you how in this post.  You don’t need to have read that article for this one to make sense, but it’s there if you want to see it.

Let’s make an emoji image

The three steps we’re using to create an emoji image are:

  • Create an emoji-shaped cutout in SVG
  • Convert the SVG code to a DataURL by URL encoding and prefixing it with data:image/svg+xml
  • Use the DataURL as the url() value of an element’s background-image.

Here’s the SVG code that creates the emoji shaped cutout:

<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='0' y='130px' font-size='130px'>&#x1f995;</text> </clipPath> <text x='0' y='130px' font-size='130px' clip-path='url(#emojiClipPath)'>&#x1f995;</text> </svg>

What’s happening here is we’re providing a <text> element with an emoji character for a <clipPath>. A clip path is an outline of a region to be kept visible when that clip path is applied to an element. In our code, that outline is the shape of the emoji character.

Then the emoji’s clip path is referenced by a <text> element carrying the same emoji character, using its clip-path property, creating a cutout in the shape of the emoji.

Now, we convert the SVG code to a DataURL. You can URL encode it by hand or use online tools (like this one!) that can do it for you.

Here’s the resulted DataURL, used as the url() value for the background image of an .emoji element in CSS:

.emoji { background: url("data:image/svg+xml,<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='0' y='130px' font-size='130px'>&#x1f995;</text> </clipPath> <text x='0' y='130px' font-size='130px' clip-path='url(%23emojiClipPath)'>&#x1f995;</text></svg>"); }

If we were to stop here and give the .emoji element dimensions, we’d see our character displayed as a background image:

CodePen Embed Fallback Now let’s turn this into a CSS Shape

We can do this in two steps:

  • Float the element with the emoji background
  • Use the DataURL as the url() value for the element’s shape-outside property
.emoji { --image-url: url("data:image/svg+xml,<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='0' y='130px' font-size='130px'>&#x1f995;</text> </clipPath> <text x='0' y='130px' font-size='130px' clip-path='url(#emojiClipPath)'>&#x1f995;</text></svg>"); background: var(--image-url); float: left; height: 150px; shape-outside: var(--image-url); width: 150px; margin-left: -6px; }

We placed the DataURL in a custom property, --image-url, so we can easily refer it in both the background and the shape-outside properties without repeating that big ol’ string of encoded SVG multiple times.

Now, any inline content near the floated .emoji element will flow in the shape of the emoji. We can adjust things even further with margin or shape-margin to add space around the shape.

CodePen Embed Fallback

If you want a color-blocked emoji shape, you can do that by applying the clip path to a <rect> element in the SVG:

<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='0' y='130px' font-size='130px'>&#x1f995;</text> </clipPath> <rect x='0' y='0' fill='green' width='150px' height='150px' clip-path='url(#emojiClipPath)'/> </svg> CodePen Embed Fallback

The same technique will work with letters!

CodePen Embed Fallback

Just note that Firefox doesn’t always render the emoji shape. We can work around that by updating the SVG code.

<svg xmlns='http://www.w3.org/2000/svg' width='150px' height='150px'> <foreignObject width='150px' height='150px'> <div xmlns='http://www.w3.org/1999/xhtml' style='width:150px;height:150px;line-height:150px;text-align:center;color:transparent;text-shadow: 0 0 black;font-size:130px;'>&#x1f9d7;</div> </foreignObject> </svg>

This creates a block-colored emoji shape by making the emoji transparent and giving it text-shadow with inline CSS. The <div> containing the emoji and inline CSS style is then inserted into a <foreignObject> element of SVG so the HTML <div> code can be used inside the SVG namespace. The rest of the code in this technique is same as the last one.

CodePen Embed Fallback Now we need to center the shape

Since CSS Shapes can only be applied to floated elements, the text flows either to the right or left of the element depending on which side it’s floated. To center the element and the shape, we’ll do the following:

  • Split the emoji in half
  • Float the left-half of the emoji to the right, and the right-half to the left
  • Put both sides together!

One caveat to this strategy: if you’re using running sentences in the design, you’ll need to manually align the letters on both sides.

Here’s what we’re aiming to make:

CodePen Embed Fallback

First, we see the HTML for the left and right sides of the design. They are identical.

<div id="design"> <p id="leftSide">A C G T A <!-- more characters --> C G T A C G T A C G T <span class="emoji"></span>A C G <!-- more characters --> C G T </p> <p id="rightSide">A C G T A <!-- more characters --> C G T A C G T A C G T <span class="emoji"></span>A C G <!-- more characters --> C G T </p> </div>

p#leftSide and p#rightSide inside #design are arranged side-by-side in a grid.

#design { border-radius: 50%; /* A circle */ box-shadow: 6px 6px 20px silver; display: grid; grid: "1fr 1fr"; /* A grid with two columns */ overflow: hidden; width: 400px; height: 400px; }

Here’s the CSS for the emoji:

span.emoji { filter: drop-shadow(15px 15px 5px green); shape-margin: 10px; width: 75px; height: 150px; } /* Left half of the emoji */ p#leftSide>span.emoji { --image-url:url("data:image/svg+xml,<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='0' y='130px' font-size='130px'>&#x1f98e;</text> </clipPath> <rect x='0' y='0' width='150px' height='150px' clip-path='url(%23emojiClipPath)'/></svg>"); background-image: var(--image-url); float: right; shape-outside: var(--image-url); } /* Right half of the emoji */ p#rightSide>span.emoji { --image-url:url("data:image/svg+xml,<svg width='150px' height='150px' xmlns='http://www.w3.org/2000/svg'> <clipPath id='emojiClipPath'> <text x='-75px' y='130px' font-size='130px'>&#x1f98e;</text> </clipPath> <rect x='0' y='0' width='150px' height='150px' clip-path='url(%23emojiClipPath)'/></svg>"); background-image: var(--image-url); float: left; shape-outside: var(--image-url); }

The width of the <span> elements that hold the emoji images (span.emoji) is 75px whereas the width of the SVG emoji images is 150px. This automatically crops the image in half when displayed inside the spans.

On the right side of the design, with the left-floated emoji (p#rightSide>span.emoji), we need to move the emoji halfway to the left to show the right-half, so the x value in the <text> in the DataURL is changed to 75px. That’s the only difference in the DataURLs from the left and right sides of the design.

Here’s that result once again:

That’s it! You can try the above method to center any CSS Shape as long as you can split the element up into two and put the halves back together with CSS.

The post Creating CSS Shapes with Emoji appeared first on CSS-Tricks.

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

CSS in 3D: Learning to Think in Cubes Instead of Boxes

Css Tricks - Fri, 10/23/2020 - 4:19am

My path to learning CSS was a little unorthodox. I didn’t start as a front-end developer. I was a Java developer. In fact, my earliest recollections of CSS were picking colors for things in Visual Studio.

It wasn’t until later that I got to tackle and find my love for the front end. And exploring CSS came later. When it did, it was around the time CSS3 was taking off. 3D and animation were the cool kids on the block. They almost shaped my learning of CSS. They drew me in and shaped (pun intended) my understanding of CSS more than other things, like layout, color, etc.

What I’m getting at is I’ve been doing the whole 3D CSS thing a minute. And as with anything you spend a lot of time with, you end up refining your process over the years as you hone that skill. This article is a look at how I’m currently approaching 3D CSS and goes over some tips and tricks that might help you!

https://codepen.io/jh3y/pen/mLaXRe Everything’s a cuboid

For most things, we can use a cuboid. We can create more complex shapes, for sure but they usually take a little more consideration. Curves are particularly hard and there are some tricks for handling them (but more on that later).

We aren’t going to walk through how to make a cuboid in CSS. We can reference Ana Tudor’s post for that, or check out this screencast of me making one:

At its core, we use one element to wrap our cuboid and then transform six elements within. Each element acts as a side to our cuboid. It’s important that we apply transform-style: preserve-3d. And it’s not a bad idea to apply it everywhere. It’s likely we’ll deal with nested cuboids when things get more complex. Trying to debug a missing transform-style while hopping between browsers can be painful.

* { transform-style: preserve-3d; }

For your 3D creations that are more than a few faces, try and imagine the whole scene built from cuboids. For a real example, consider this demo of a 3D book. It’s four cuboids. One for each cover, one for the spine, and one for the pages. The use of background-image does the rest for us.

Setting a scene

We’re going to use cuboids like LEGO pieces. But, we can make our lives a little easier by setting a scene and creating a plane. That plane is where our creation will sit and makes it easier for us to rotate and move the whole creation.

For me, when I create a scene, I like to rotate it on the X and Y axis first. Then I lay it flat with rotateX(90deg). That way, when I want to add a new cuboid to the scene, I add it inside the plane element. Another thing I will do here is to set position: absolute on all cuboids.

.plane { transform: rotateX(calc(var(--rotate-x, -24) * 1deg)) rotateY(calc(var(--rotate-y, -24) * 1deg)) rotateX(90deg) translate3d(0, 0, 0); } Start with a boilerplate

Creating cuboids of various sizes and across a plane makes for a lot of repetition for each creation. For this reason, I use Pug to create my cuboids via a mixin. If you’re not familiar with Pug, I wrote a 5-minute intro.

A typical scene looks like this:

//- Front //- Back //- Right //- Left //- Top //- Bottom mixin cuboid(className) .cuboid(class=className) - let s = 0 while s < 6 .cuboid__side - s++ .scene //- Plane that all the 3D stuff sits on .plane +cuboid('first-cuboid')

As for the CSS. My cuboid class is currently looking like this:

.cuboid { // Defaults --width: 15; --height: 10; --depth: 4; height: calc(var(--depth) * 1vmin); width: calc(var(--width) * 1vmin); transform-style: preserve-3d; position: absolute; font-size: 1rem; transform: translate3d(0, 0, 5vmin); } .cuboid > div:nth-of-type(1) { height: calc(var(--height) * 1vmin); width: 100%; transform-origin: 50% 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotateX(-90deg) translate3d(0, 0, calc((var(--depth) / 2) * 1vmin)); } .cuboid > div:nth-of-type(2) { height: calc(var(--height) * 1vmin); width: 100%; transform-origin: 50% 50%; transform: translate(-50%, -50%) rotateX(-90deg) rotateY(180deg) translate3d(0, 0, calc((var(--depth) / 2) * 1vmin)); position: absolute; top: 50%; left: 50%; } .cuboid > div:nth-of-type(3) { height: calc(var(--height) * 1vmin); width: calc(var(--depth) * 1vmin); transform: translate(-50%, -50%) rotateX(-90deg) rotateY(90deg) translate3d(0, 0, calc((var(--width) / 2) * 1vmin)); position: absolute; top: 50%; left: 50%; } .cuboid > div:nth-of-type(4) { height: calc(var(--height) * 1vmin); width: calc(var(--depth) * 1vmin); transform: translate(-50%, -50%) rotateX(-90deg) rotateY(-90deg) translate3d(0, 0, calc((var(--width) / 2) * 1vmin)); position: absolute; top: 50%; left: 50%; } .cuboid > div:nth-of-type(5) { height: calc(var(--depth) * 1vmin); width: calc(var(--width) * 1vmin); transform: translate(-50%, -50%) translate3d(0, 0, calc((var(--height) / 2) * 1vmin)); position: absolute; top: 50%; left: 50%; } .cuboid > div:nth-of-type(6) { height: calc(var(--depth) * 1vmin); width: calc(var(--width) * 1vmin); transform: translate(-50%, -50%) translate3d(0, 0, calc((var(--height) / 2) * -1vmin)) rotateX(180deg); position: absolute; top: 50%; left: 50%; }

Which, by default, gives me something like this:

Powered by CSS variables

You may have noticed a fair few CSS variables (aka custom properties) in there. This is a big time-saver. I’m powering my cuboids with CSS variables.

  • --width: The width of a cuboid on the plane
  • --height: The height of a cuboid on the plane
  • --depth: The depth of a cuboid on the plane
  • --x: The X position on the plane
  • --y: The Y position on the plane

I use vmin mostly as my sizing unit to keep everything responsive. If I’m creating something to scale, I might create a responsive unit. We mentioned this technique in a previous article. Again, I lay the plane down flat. Now I can refer to my cuboids as having height, width, and depth. This demo shows how we can move a cuboid around the plane changing its dimensions.

CodePen Embed Fallback Debugging with dat.GUI

You might have noticed that little panel in the top right for some of the demos we’ve covered. That’s dat.GUI. It’s a lightweight controller library for JavaScript that super useful for debugging 3D CSS. With not much code, we can set up a panel that allows us to change CSS variables at runtime. One thing I like to do is use the panel to rotate the plane on the X and Y-axis. That way, it’s possible to see how things are lining up or work on a part that you might not see at first.

const { dat: { GUI }, } = window const CONTROLLER = new GUI() const CONFIG = { 'cuboid-height': 10, 'cuboid-width': 10, 'cuboid-depth': 10, x: 5, y: 5, z: 5, 'rotate-cuboid-x': 0, 'rotate-cuboid-y': 0, 'rotate-cuboid-z': 0, } const UPDATE = () => { Object.entries(CONFIG).forEach(([key, value]) => { document.documentElement.style.setProperty(`--${key}`, value) }) } const CUBOID_FOLDER = CONTROLLER.addFolder('Cuboid') CUBOID_FOLDER.add(CONFIG, 'cuboid-height', 1, 20, 0.1) .name('Height (vmin)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'cuboid-width', 1, 20, 0.1) .name('Width (vmin)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'cuboid-depth', 1, 20, 0.1) .name('Depth (vmin)') .onChange(UPDATE) // You have a choice at this point. Use x||y on the plane // Or, use standard transform with vmin. CUBOID_FOLDER.add(CONFIG, 'x', 0, 40, 0.1) .name('X (vmin)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'y', 0, 40, 0.1) .name('Y (vmin)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'z', -25, 25, 0.1) .name('Z (vmin)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'rotate-cuboid-x', 0, 360, 1) .name('Rotate X (deg)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'rotate-cuboid-y', 0, 360, 1) .name('Rotate Y (deg)') .onChange(UPDATE) CUBOID_FOLDER.add(CONFIG, 'rotate-cuboid-z', 0, 360, 1) .name('Rotate Z (deg)') .onChange(UPDATE) UPDATE()

If you watch the timelapse video in this tweet. You’ll notice that I rotate the plane a lot as I build up the scene.

https://twitter.com/jh3yy/status/1312126353177673732?s=20

That dat.GUI code is a little repetitive. We can create functions that will take a configuration and generate the controller. It takes a little tinkering to cater to your needs. I started playing with dynamically generated controllers in this demo.

Centering

You may have noticed that by default each cuboid is half under and half above the plane. That’s intentional. It’s also something I only recently started to do. Why? Because we want to use the containing element of our cuboids as the center of the cuboid. This makes animation easier. Especially, if we’re considering rotating around the Z-axis. I found this out when creating “CSS is Cake”. After making the cake, I then decided I wanted each slice to be interactive. I then had to go back and change my implementation to fix the rotation center of the flipping slice.

https://codepen.io/jh3y/pen/KKVGoGJ

Here I’ve broken that demo down to show the centers and how having an offset center would affect the demo.

Positioning

If we are working with a scene that’s more complex, we may split it up into different sections. This is where the concept of sub-planes comes in handy. Consider this demo where I’ve recreated my personal workspace.

https://twitter.com/jh3yy/status/1310658720746045440?s=20

There’s quite a bit going on here and it’s hard to keep track of all the cuboids. For that, we can introduce sub-planes. Let’s break down that demo. The chair has its own sub-plane. This makes it easier to move it around the scene and rotate it — among other things — without affecting anything else. In fact, we can even spin the top without moving the feet!

Aesthetics

Once we’ve got a structure, it’s time to work on the aesthetics. This all depends on what you’re making. But you can get some quick wins from using certain techniques. I tend to start by making things “ugly” then go back and make CSS variables for all the colors and apply them. Three shades for a certain thing allows us to differentiate the sides of a cuboid visually. Consider this toaster example. Three shades cover the sides of the toaster:

https://codepen.io/jh3y/pen/KKVjLrx

Our Pug mixin from earlier allows us to define class names for a cuboid. Applying color to a side usually looks something like this:

/* The front face uses a linear-gradient to apply the shimmer effect */ .toaster__body > div:nth-of-type(1) { background: linear-gradient(120deg, transparent 10%, var(--shine) 10% 20%, transparent 20% 25%, var(--shine) 25% 30%, transparent 30%), var(--shade-one); } .toaster__body > div:nth-of-type(2) { background: var(--shade-one); } .toaster__body > div:nth-of-type(3), .toaster__body > div:nth-of-type(4) { background: var(--shade-three); } .toaster__body > div:nth-of-type(5), .toaster__body > div:nth-of-type(6) { background: var(--shade-two); }

It’s a little tricky to include extra elements with our Pug mixin. But let’s not forget, every side to our cuboid offers two pseudo-elements. We can use these for various details. For example, the toaster slot and the slot for the handle on the side are pseudo-elements.

Another trick is to use background-image for adding details. For example, consider the 3D workspace. We can use background layers to create shading. We can use actual images to create textured surfaces. The flooring and the rug are a repeating background-image. In fact, using a pseudo-element for textures is great because then we can transform them if needed, like rotating a tiled image. I’ve also found that I get flickering in some cases working directly with a cuboid side.

https://codepen.io/jh3y/pen/XWdQBRx

One issue with using an image for texture is how we create different shades. We need shades to differentiate the different sides. That’s where the filter property can help. Applying a brightness``() filter to the different sides of a cuboid can lighten or darken them. Consider this CSS flipping table. All the surfaces are using a texture image. But to differentiate the sides, brightness filters are applied.

https://codepen.io/jh3y/pen/xJXvjP Smoke and mirrors perspective

How about shapes — or features we want to create that seem impossible — using a finite set of elements? Sometimes we can trick the eye with a little smoke and mirrors. We can provide a “faux” like sense of 3D. The Zdog library does this well and is a good example of this.

Consider this bundle of balloons. The strings holding them use the correct perspective and each has its own rotation, tilt, etc. But the balloons themselves are flat. If we rotate the plane, the balloons maintain the counter plane rotation. And this gives that “faux” 3D impression. Try out the demo and switch off the countering.

https://codepen.io/jh3y/pen/NWNVgJw

Sometimes it takes a little out-of-the-box thinking. I had a house plant suggested to me as I built the 3D workspace. I have a few in the room. My initial thought was, “No, I can make a square pot, and how would I make all the leaves?” Well actually, we can use some eye tricks on this one too. Grab a stock image of some leaves or a plant. Remove the background with a tool like remove.bg. Then position many images in the same spot but rotate them each a certain amount. Now, when they’re rotated, we get the impression of a 3D plant.

Tackling awkward shapes

Awkward shapes are tough to cover in a generic way. Every creation has its own hurdles. But, there is a couple of examples that could help give you ideas for tackling things. I recently read an article about the UX of LEGO interface panels. In fact, approaching 3D CSS work like it’s a LEGO set isn’t a bad idea. But the LEGO interface panel is a shape we could make with CSS (minus the studs — I only recently learned this is what they are called). It’s a cuboid to start with. Then we can clip the top face, make the end face transparent, and rotate a pseudo-element to join it up. We can use the pseudo-element for adding the details with some background layers. Try turning the wireframe on and off in the demo below. If we want the exact heights and angles for the faces, we can use some math to workout the hypoteneuse etc.

Another awkward thing to cover is curves. Spherical shapes are not in the CSS wheelhouse. We have various options at this point. One option is to embrace that fact and create polygons with a finite number of sides. Another is to create rounded shapes and use the rotation method we mentioned with the plant. Each of these options could work. But again, it’s on a use case basis. Each has pros and cons. With the polygon, we surrender the curves or use so many elements that we get an almost curve. The latter could result in performance issues. With the perspective trick, we may also end up with performance issues depending. We also surrender being able to style the “sides” of the shape as there aren’t any.

Z fighting

Last, but not least, it’s worth mentioning “Z-fighting.” This is where certain elements on a plane may overlap or cause an undesirable flicker. It’s hard to give good examples of this. There’s not a generic solution for it. It’s something to tackle on a case-by-case basis. The main strategy is to order things in the DOM as appropriate. But sometimes that’s not the only issue.

Being accurate can sometimes cause issues. Let’s refer to the 3D workspace again. Consider the canvas on the wall. The shadow is a pseudo-element. If we place the canvas exactly against the wall, we are going to hit issues. If we do that, the shadow and the wall are going to fight for the front position. To combat this, we can translate things by a slight amount. That will solve the issue and declare what should sit in front.

Try resizing this demo with the “Canvas offset” on and off. Notice how the shadow flickers when there is no offset? That’s because the shadow and the wall are fighting for view. The offset sets the --x to a fraction of 1vmin that we’ve named --cm. That’s a responsive unit being used for that creation.

That’s “it”!

Take your CSS to another dimension. Use some of my tips, create your own, share them, and share your 3D creations! Yes, making 3D things in CSS can be tough and is definitely a process that we can refine as we go along. Different approaches work for different people and patience is a required ingredient. I’m interested to see where you take your approach!

The most important thing? Have fun with it!

The post CSS in 3D: Learning to Think in Cubes Instead of Boxes appeared first on CSS-Tricks.

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

Notes on the web, take 2

QuirksBlog - Thu, 10/22/2020 - 5:23am

Today I updated the Thidrekssaga mini site with a first attempt at a decent mobile view. I also did some work on the mobile view for the notes, and I’m asking for a quick review.

As I discussed two weeks ago I want the notes to my texts to be visible at all times in order to emulate the footnote experience in books. I was worried about mobile devices, since with their narrow screens there is not much space to show both the main text and the notes.

I was afraid I’d have to show the notes under the paragraph they belong to, but today I figured out a way to avoid that and keep them in the margin. My question is if this system is good enough.

Chapter 352 is a good test since it contains a lot of notes in a single paragraph. So please go to that chapter on a mobile phone of your choice and try to access the notes.

Principles:

  1. Although it is impossible to show the full notes on narrow mobile screens, I want to show at least a little bit of them so that users know there are notes.
  2. When touching/clicking the notes they should not only be highlighted, but also scroll into view for easy reading. This is the bit of interaction I’d particularly like feedback on. Good idea or bad? If bad, why?

The notes are still positioned absolutely, and thay may mean they cover one another. The feedback to my previous article convinced me that this needs to be changed, but I haven’t actually done so yet. So please do not comment on this problem. I have a vague idea what to do, but that was predicated on the idea that I had to show the notes below the paragraphs on mobile. If that turns out to be unnecessary I will have to revise my idea. (Also, it would require some serious grid magic.)

On my iPad with iOS 14.1, Safari refuses to scroll smoothly to the notes. Apparently it does not support the behavior: 'smooth' option of scrollIntoView(). That surprises me a bit, since usually Apple is gung ho on smooth animations and behaviours. I assume there’s a performance problem in extreme scenarios. A quick search for alternative syntax or something yielded nothing.

Technical details

Technically it’s quite simple. I added the meta viewport and a single simple body rule that does away with most of the left margin but adds a fat padding-right.

@media all and (max-width: 850px) { body { margin-left: 1em; padding-right: 2em; } }

The padding-right makes the paragraphs contained in the body somewhat less than 100% wode. Since the notes are positioned relative to the paragraphs, they, too, are drawn leftward, and that makes them just barely visible on the right edge of small screens — enough to alert the user they’re there, or so I hope.

One drawback of this fat padding on the body is that when the user double-taps on a paragraph of main text the browser zooms in to the width of the paragraph, and not the body. This may mean the notes are not visible any more. I’m not yet sure what to do about this, or, indeed, whether to do anything at all.

e.target.ref.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end', });

A simple scrollIntoView(), called onclick, delivers the finishing touch. This makes the browser scroll to the note or back to the marker if necessary; and if it’s not necessary nothing happens.

  • behavior: 'smooth': scroll smoothly. Doesn’t work on iOS.
  • block: 'nearest': don’t scroll in the block direction (i.e. up or down) unless required — and it should never be required. I don’t fully understand this option yet, but it does what I want.
  • inline: 'end': in the inline direction (i.e. left to right), scroll to the very end (the right). This makes the note scroll fully into view, and markers are also scrolled as much to the right as possible, which effectively means the main tex column is fully in view.

Create an FAQ Slack app with Netlify functions and FaunaDB

Css Tricks - Thu, 10/22/2020 - 4:49am

Sometimes, when you’re looking for a quick answer, it’s really useful to have an FAQ system in place, rather than waiting for someone to respond to a question. Wouldn’t it be great if Slack could just answer these FAQs for us? In this tutorial, we’re going to be making just that: a slash command for Slack that will answer user FAQs. We’ll be storing our answers in FaunaDB, using FQL to search the database, and utilising a Netlify function to provide a serverless endpoint to connect Slack and FaunaDB.

Prerequisites

This tutorial assumes you have the following requirements:

  • Github account, used to log in to Netlify and Fauna, as well as storing our code
  • Slack workspace with permission to create and install new apps
  • Node.js v12
Create npm package

To get started, create a new folder and initialise a npm package by using your package manager of choice and run npm init -y from inside the folder. After the package has been created, we have a few npm packages to install.

Run this to install all the packages we will need for this tutorial:

npm install express body-parser faunadb encoding serverless-http netlify-lambda

These packages are explained below, but if you are already familiar with them, feel free to skip ahead.

Encoding has been installed due to a plugin error occurring in @netlify/plugin-functions-core at the time of writing and may not be needed when you follow this tutorial.

Packages

Express is a web application framework that will allow us to simplify writing multiple endpoints for our function. Netlify functions require handlers for each endpoint, but express combined with serverless-http will allow us to write the endpoints all in one place.

Body-parser is an express middleware which will take care of the application/x-www-form-urlencoded data Slack will be sending to our function.

Faunadb is an npm module that allows us to interact with the database through the FaunaDB Javascript driver. It allows us to pass queries from our function to the database, in order to get the answers

Serverless-http is a module that wraps Express applications to the format expected by Netlify functions, meaning we won’t have to rewrite our code when we shift from local development to Netlify.

Netlify-lambda is a tool which will allow us to build and serve our functions locally, in the same way they will be built and deployed on Netlify. This means we can develop locally before pushing our code to Netlify, increasing the speed of our workflow.

Create a function

With our npm packages installed, it’s time to begin work on the function. We’ll be using serverless to wrap an express app, which will allow us to deploy it to Netlify later. To get started, create a file called netlify.toml, and add the following into it:

[build] functions = "functions"

We will use a .gitignore file, to prevent our node_modules and functions folders from being added to git later. Create a file called .gitignore, and add the following:

functions/

node_modules/

We will also need a folder called src, and a file inside it called server.js. Your final file structure should look like:

With this in place, create a basic express app by inserting the code below into server.js:

const express = require("express"); const bodyParser = require("body-parser"); const fauna = require("faunadb"); const serverless = require("serverless-http"); const app = express(); module.exports.handler = serverless(app);

Check out the final line; it looks a little different to a regular express app. Rather than listening on a port, we’re passing our app into serverless and using this as our handler, so that Netlify can invoke our function.

Let’s set up our body parser to use application/x-www-form-urlencoded data, as well as putting a router in place. Add the following to server.js after defining app: 

const router = express.Router(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use("/.netlify/functions/server", router);

Notice that the router is using /.netlify/functions/server as an endpoint. This is so that Netlify will be able to correctly deploy the function later in the tutorial. This means we will need to add this to any base URLs, in order to invoke the function.

Create a test route

With a basic app in place, let’s create a test route to check everything is working. Insert the following code to create a simple GET route, that returns a simple json object:

router.get("/test", (req, res) => { res.json({ hello: "world" }); });

With this route in place, let’s spin up our function on localhost, and check that we get a response. We’ll be using netlify-lambda to serve our app, so that we can imitate a Netlify function locally on port 9000. In our package.json, add the following lines into the scripts section:

"start": "./node_modules/.bin/netlify-lambda serve src", "build": "./node_modules/.bin/netlify-lambda build src"

With this in place, after saving the file, we can run npm start to begin netlify-lambda on port 9000.

The build command will be used when we deploy to Netlify later.

Once it is up and running, we can visit http://localhost:9000/.netlify/functions/server/test to check our function is working as expected.

The great thing about netlify-lambda is it will listen for changes to our code, and automatically recompile whenever we update something, so we can leave it running for the duration of this tutorial.

Start ngrok URL

Now we have a test route working on our local machine, let’s make it available online. To do this, we’ll be using ngrok, a npm package that provides a public URL for our function. If you don’t have ngrok installed already, first run npm install -g ngrok to globally install it on your machine. Then run ngrok http 9000 which will automatically direct traffic to our function running on port 9000.

After starting ngrok, you should see a forwarding URL in the terminal, which we can visit to confirm our server is available online. Copy this base URL to your browser, and follow it with /.netlify/functions/server/test. You should see the same result as when we made our calls on localhost, which means we can now use this URL as an endpoint for Slack!

Each time you restart ngrok, it creates a new URL, so if you need to stop it at any point, you will need to update your URL endpoint in Slack.

Setting up Slack

Now that we have a function in place, it’s time to move to Slack to create the app and slash command. We will have to deploy this app to our workspace, as well as making a few updates to our code to connect our function. For a more in depth set of instructions on how to create a new slash command, you can follow the official Slack documentation. For a streamlined set of instructions, follow along below:

Create a new Slack app

First off, let’s create our new Slack app for these FAQs. Visit https://api.slack.com/apps and select Create New App to begin. Give your app a name (I used Fauna FAQ), and select a development workspace for the app.

Create a slash command

After creating the app, we need to add a slash command to it, so that we can interact with the app. Select slash commands from the menu after the app has been created, then create a new command. Fill in the following form with the name of your command (I used /faq) as well as providing the URL from ngrok. Don’t forget to add /.netlify/functions/server/ to the end!

Install app to workspace

Once you have created your slash command, click on basic information in the sidebar on the left to return to the app’s main page. From here, select the dropdown “Install app to your workspace” and click the button to install it.

Once you have allowed access, the app will be installed, and you’ll be able to start using the slash command in your workspace.

Update the function

With our new app in place, we’ll need to create a new endpoint for Slack to send the requests to. For this, we’ll use the root endpoint for simplicity. The endpoint will need to be able to take a post request with application/x-www-form-urlencoded data, then return a 200 status response with a message. To do this, let’s create a new post route at the root by adding the following code to server.js:

router.post("/", async (req, res) => { });

Now that we have our endpoint, we can also extract and view the text that has been sent by slack by adding the following line before we set the status:

const text = req.body.text; console.log(`Input text: ${text}`);

For now, we’ll just pass this text into the response and send it back instantly, to ensure the slack app and function are communicating.

res.status(200); res.send(text);

Now, when you type /faq <somequestion> on a slack channel, you should get back the same message from the slack slash command.

Formatting the response

Rather than just sending back plaintext, we can make use of Slack’s Block Kit to use specialised UI elements to improve the look of our answers. If you want to create a more complex layout, Slack provides a Block Kit builder to visually design your layout.

For now, we’re going to keep things simple, and just provide a response where each answer is separated by a divider. Add the following function to your server.js file after the post route:

const format = (answers) => { if (answers.length == 0) { answers = ["No answers found"]; } let formatted = { blocks: [], }; for (answer of answers) { formatted["blocks"].push({ type: "divider", }); formatted["blocks"].push({ type: "section", text: { type: "mrkdwn", text: answer, }, }); } return formatted; };

With this in place, we now need to pass our answers into this function, to format the answers before returning them to Slack. Update the following in the root post route:

let answers = text; const formattedAnswers = format(answers);

Now when we enter the same command to the slash app, we should get back the same message, but this time in a formatted version!

Setting up Fauna

With our slack app in place, and a function to connect to it, we now need to start working on the database to store our answers. If you’ve never set up a database with FaunaDB before, there is some great documentation on how to quickly get started. A brief step-by-step overview for the database and collection is included below:

Create database

First, we’ll need to create a new database. After logging into the Fauna dashboard online, click New Database. Give your new database a name you’ll remember (I used “slack-faq”) and save the database.

Create collection

With this database in place, we now need a collection. Click the “New Collection” button that should appear on your dashboard, and give your collection a name (I used “faq”). The history days and TTL values can be left as their defaults, but you should ensure you don’t add a value to the TTL field, as we don’t want our documents to be removed automatically after a certain time.

Add question / answer documents

Now we have a database and collection in place, we can start adding some documents to it. Each document should follow the structure:

{ question: "a question string", answer: "an answer string", qTokens: [ "first token", "second token", "third token" ] }

The qToken values should be key terms in the question, as we will use them for a tokenized search when we can’t match a question exactly. You can add as many qTokens as you like for each question. The more relevant the tokens are, the more accurate results will be. For example, if our question is “where are the bathrooms”, we should include the qTokens “bathroom”, “bathrooms”, “toilet”, “toilets” and any other terms you may think people will search for when trying to find information about a bathroom.

The questions I used to develop a proof of concept are as follows:

{ question: "where is the lobby", answer: "On the third floor", qTokens: ["lobby", "reception"], }, { question: "when is payday", answer: "On the first Monday of each month", qTokens: ["payday", "pay", "paid"], }, { question: "when is lunch", answer: "Lunch break is *12 - 1pm*", qTokens: ["lunch", "break", "eat"], }, { question: "where are the bathrooms", answer: "Next to the elevators on each floor", qTokens: ["toilet", "bathroom", "toilets", "bathrooms"], }, { question: "when are my breaks", answer: "You can take a break whenever you want", qTokens: ["break", "breaks"], }

Feel free to take this time to add as many documents as you like, and as many qTokens as you think each question needs, then we’ll move on to the next step.

Creating Indexes

With these questions in place, we will create two indexes to allow us to search the database. First, create an index called “answers_by_question”, selecting question as the term and answer as the value. This will allow us to search all answers by their associated question.

Then, create an index called “answers_by_qTokens”, selecting qTokens as the term and answer as the value. We will use this index to allow us to search through the qTokens of all items in the database.

Searching the database

To run a search in our database, we will do two things. First, we’ll run a search for an exact match to the question, so we can provide a single answer to the user. Second, if this search doesn’t find a result, we’ll do a search on the qTokens each answer has, returning any results that provide a match. We’ll use Fauna’s online shell to demonstrate and explain these queries, before using them in our function.

Exact Match

Before searching the tokens, we’ll test whether we can match the input question exactly, as this will allow for the best answer to what the user has asked. To search our questions, we will match against the “answers_by_question” index, then paginate our answers. Copy the following code into the online Fauna shell to see this in action:

q.Paginate(q.Match(q.Index("answers_by_question"), "where is the lobby"))

If you have a question matching the “where is the lobby” example above, you should see the expected answer of “On the third floor” as a result.

Searching the tokens

For cases where there is no exact match on the database, we will have to use our qTokens to find any relevant answers. For this, we will match against the “answers_by_qTokens” index we created and again paginate our answers. Copy the following into the online shell to see how this works:

q.Paginate(q.Match(q.Index("answers_by_qTokens"), "break"))

If you have any questions with the qToken “break” from the example questions, you should see all answers returned as a result.

Connect function to Fauna

We have our searches figured out, but currently we can only run them from the online shell. To use these in our function, there is some configuration required, as well as an update to our function’s code.

Function configuration

To connect to Fauna from our function, we will need to create a server key. From your database’s dashboard, select security in the left hand sidebar, and create a new key. Give your new key a name you will recognise, and ensure that the dropdown has Server selected, not Admin. Finally, once the key has been created, add the following code to server.js before the test route, replacing the <secretKey> value with the secret provided by Fauna.

const q = fauna.query; const client = new fauna.Client({ secret: "<secretKey>", });

It would be preferred to store this key in an environment variable in Netlify, rather than directly in the code, but that is beyond the scope of this tutorial. If you would like to use environment variables, this Netlify post explains how to do so.

Update function code

To include our new search queries in the function, copy the following code into server.js after the post route:

const searchText = async (text) => { console.log("Beginning searchText"); const answer = await client.query( q.Paginate(q.Match(q.Index("answers_by_question"), text)) ); console.log(`searchText response: ${answer.data}`); return answer.data; }; const getTokenResponse = async (text) => { console.log("Beginning getTokenResponse"); let answers = []; const questionTokens = text.split(/[ ]+/); console.log(`Tokens: ${questionTokens}`); for (token of questionTokens) { const tokenResponse = await client.query( q.Paginate(q.Match(q.Index("answers_by_qTokens"), text)) ); answers = [...answers, ...tokenResponse.data]; } console.log(`Token answers: ${answers}`); return answers; };

These functions replicate the same functionality as the queries we previously ran in the online Fauna shell, but now we can utilise them from our function.

Deploy to Netlify

Now the function is searching the database, the only thing left to do is put it on the cloud, rather than a local machine. To do this, we’ll be making use of a Netlify function deployed from a GitHub repository.

First things first, add a new repo on Github, and push your code to it. Once the code is there, go to Netlify and either sign up or log in using your Github profile. From the home page of Netlify, select “New site from git” to deploy a new site, using the repo you’ve just created in Github.

If you have never deployed a site in Netlify before, this post explains the process to deploy from git.

Ensure while you are creating the new site, that your build command is set to npm run build, to have Netlify build the function before deployment. The publish directory can be left blank, as we are only deploying a function, rather than any pages.

Netlify will now build and deploy your repo, generating a unique URL for the site deployment. We can use this base URL to access the test endpoint of our function from earlier, to ensure things are working.

The last thing to do is update the Slack endpoint to our new URL! Navigate to your app, then select ‘slash commands’ in the left sidebar. Click on the pencil icon to edit the slash command and paste in the new URL for the function. Finally, you can use your new slash command in any authorised Slack channels!

Conclusion

There you have it, an entirely serverless, functional slack slash command. We have used FaunaDB to store our answers and connected to it through a Netlify function. Also, by using Express, we have the flexibility to add further endpoints to the function for adding new questions, or anything else you can think up to further extend this project! Hopefully now, instead of waiting around for someone to answer your questions, you can just use /faq and get the answer instantly!

Matthew Williams is a software engineer from Melbourne, Australia who believes the future of technology is serverless. If you’re interested in more from him, check out his Medium articles, or his GitHub repos.

The post Create an FAQ Slack app with Netlify functions and FaunaDB appeared first on CSS-Tricks.

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

A Primer on the Different Types of Browser Storage

Css Tricks - Wed, 10/21/2020 - 4:41am

In back-end development, storage is a common part of the job. Application data is stored in databases, files in object storage, transient data in caches… there are seemingly endless possibilities for storing any sort of data. But data storage isn’t limited only to the back end. The front end (the browser) is equipped with many options to store data as well. We can boost our application performance, save user preferences, keep the application state across multiple sessions, or even different computers, by utilizing this storage.

In this article, we will go through the different possibilities to store data in the browser. We will cover three use cases for each method to grasp the pros and cons. In the end, you will be able to decide what storage is the best fit for your use case. So let’s start!

The localStorage API

localStorage is one of the most popular storage options in the browser and the go-to for many developers. The data is stored across sessions, never shared with the server, and is available for all pages under the same protocol and domain. Storage is limited to ~5MB.

Surprisingly, the Google Chrome team doesn’t recommend using this option as it blocks the main thread and is not accessible to web workers and service workers. They launched an experiment, KV Storage, as a better version, but it was just a trial that doesn’t seem to have gone anywhere just yet.

The localStorage API is available as window.localStorage and can save only UTF-16 strings. We must make sure to convert data to strings before saving it into localStorage. The main three functions are:

  • setItem('key', 'value')
  • getItem('key')
  • removeItem('key')

They’re all synchronous, which makes it simple to work with, but they block the main thread.

It’s worth mentioning that localStorage has a twin called sessionStorage. The only difference is that data stored in sessionStorage will last only for the current session, but the API is the same.

Let’s see it in action. The first example demonstrates how to use localStorage for storing the user’s preferences. In our case, it’s a boolean property that turns on or off the dark theme of our site.

CodePen Embed Fallback

You can check the checkbox and refresh the page to see that the state is saved across sessions. Take a look at the save and load functions to see how I convert the value to string and how I parse it. It’s important to remember that we can store only strings.

This second example loads Pokémon names from the PokéAPI.

CodePen Embed Fallback

We send a GET request using fetch and list all the names in a ul element. Upon getting the response, we cache it in the localStorage so our next visit can be much faster or even work offline. We have to use JSON.stringify to convert the data to string and JSON.parse to read it from the cache.

In this last example, I demonstrate a use case where the user can browse through different Pokémon pages, and the current page is saved for the next visits.

CodePen Embed Fallback

The issue with localStorage, in this case, is that the state is saved locally. This behavior doesn’t allow us to share the desired page with our friends. Later, we will see how to overcome this issue.

We will use these three examples in the next storage options as well. I forked the Pens and just changed the relevant functions. The overall skeleton is the same for all methods.

The IndexedDB API

IndexedDB is a modern storage solution in the browser. It can store a significant amount of structured data — even files, and blobs. Like every database, IndexedDB indexes the data for running queries efficiently. It’s more complex to use IndexedDB. We have to create a database, tables, and use transactions.

Compared to localStorage , IndexedDB requires a lot more code. In the examples, I use the native API with a Promise wrapper, but I highly recommend using third-party libraries to help you out. My recommendation is localForage because it uses the same localStorage API but implements it in a progressive enhancement manner, meaning if your browser supports IndexedDB, it will use it; and if not, it will fall back to localStorage.

Let’s code, and head over to our user preferences example!

CodePen Embed Fallback

idb is the Promise wrapper that we use instead of working with a low-level events-based API. They’re almost identical, so don’t worry. The first thing to notice is that every access to the database is async, meaning we don’t block the main thread. Compared to localStorage, this is a major advantage.

We need to open a connection to our database so it will be available throughout the app for reading and writing. We give our database a name, my-db, a schema version, 1, and an update function to apply changes between versions. This is very similar to database migrations. Our database schema is simple: only one object store, preferences. An object store is the equivalent of an SQL table. To write or read from the database, we must use transactions. This is the tedious part of using IndexedDB. Have a look at the new save and load functions in the demo.

No doubt that IndexedDB has much more overhead and the learning curve is steeper compared to localStorage. For the key value cases, it might make more sense to use localStorage or a third-party library that will help us be more productive.

CodePen Embed Fallback

Application data, such as in our Pokémon example, is the forte of IndexedDB. You can store hundreds of megabytes and even more in this database. You can store all the Pokémon in IndexedDB and have them available offline and even indexed! This is definitely the one to choose for storing app data.

I skipped the implementation of the third example, as IndexedDB doesn’t introduce any difference in this case compared to localStorage. Even with IndexedDB, the user will still not share the selected page with others or bookmark it for future use. They’re both not the right fit for this use case.

Cookies

Using cookies is a unique storage option. It’s the only storage that is also shared with the server. Cookies are sent as part of every request. It can be when the user browses through pages in our app or when the user sends Ajax requests. This allows us to create a shared state between the client and the server, and also share state between multiple applications in different subdomains. This is not possible by other storage options that are described in this article. One caveat: cookies are sent with every request, which means that we have to keep our cookies small to maintain a decent request size.

The most common use for cookies is authentication, which is out of the scope of this article. Just like the localStorage, cookies can store only strings. The cookies are concatenated into one semicolon-separated string, and they are sent in the cookie header of the request. You can set many attributes for every cookie, such as expiration, allowed domains, allowed pages, and many more.

In the examples, I show how to manipulate the cookies through the client-side, but it’s also possible to change them in your server-side application.

CodePen Embed Fallback

Saving the user’s preferences in a cookie can be a good fit if the server can utilize it somehow. For example, in the theme use case, the server can deliver the relevant CSS file and reduce potential bundle size (in case we’re doing server-side-rendering). Another use case might be to share these preferences across multiple subdomain apps without a database.

Reading and writing cookies with JavaScript is not as straightforward as you might think. To save a new cookie, you need to set document.cookie — check out the save function in the example above. I set the dark_theme cookie and add it a max-age attribute to make sure it will not expire when the tab is closed. Also, I add the SameSite and Secure attributes. These are necessary because CodePen uses iframe to run the examples, but you will not need them in most cases. Reading a cookie requires parsing the cookie string.

A cookie string looks like this:

key1=value1;key2=value2;key3=value3

So, first, we have to split the string by semicolon. Now, we have an array of cookies in the form of key1=value1, so we need to find the right element in the array. In the end, we split by the equal sign and get the last element in the new array. A bit tedious, but once you implement the getCookie function (or copy it from my example :P) you can forget it.

Saving application data in a cookie can be a bad idea! It will drastically increase the request size and will reduce application performance. Also, the server cannot benefit from this information as it’s a stale version of the information it already has in its database. If you use cookies, make sure to keep them small.

The pagination example is also not a good fit for cookies, just like localStorage and IndexedDB. The current page is a temporary state that we would like to share with others, and any of these methods do not achieve it.

URL storage

URL is not a storage, per se, but it’s a great way to create a shareable state. In practice, it means adding query parameters to the current URL that can be used to recreate the current state. The best example would be search queries and filters. If we search the term flexbox on CSS-Tricks, the URL will be updated to https://css-tricks.com/?s=flexbox. See how easy it is to share a search query once we use the URL? Another advantage is that you can simply hit the refresh button to get newer results of your query or even bookmark it.

We can save only strings in the URL, and its maximum length is limited, so we don’t have so much space. We will have to keep our state small. No one likes long and intimidating URLs.

Again, CodePen uses iframe to run the examples, so you cannot see the URL actually changing. Worry not, because all the bits and pieces are there so you can use it wherever you want.

CodePen Embed Fallback

We can access the query string through window.location.search and, lucky us, it can be parsed using the URLSearchParams class. No need to apply any complex string parsing anymore. When we want to read the current value, we can use the get function. When we want to write, we can use set. It’s not enough to only set the value; we also need to update the URL. This can be done using history.pushState or history.replaceState, depending on the behavior we want to accomplish.

I wouldn’t recommend saving a user’s preferences in the URL as we will have to add this state to every URL the user visits, and we cannot guarantee it; for example, if the user clicks on a link from Google Search.

Just like cookies, we cannot save application data in the URL as we have minimal space. And even if we did manage to store it, the URL will be long and not inviting to click. Might look like a phishing attack of sorts.

CodePen Embed Fallback

Just like our pagination example, the temporary application state is the best fit for the URL query string. Again, you cannot see the URL changes, but the URL updates with the ?page=x query parameter every time you click on a page. When the web page loads, it looks for this query parameter and fetches the right page accordingly. Now we can share this URL with our friends so they can enjoy our favorite Pokémon.

Cache API

Cache API is a storage for the network level. It is used to cache network requests and their responses. The Cache API fits perfectly with service workers. A service worker can intercept every network request, and using the Cache API, it can easily cache both the requests. The service worker can also return an existing cache item as a network response instead of fetching it from the server. By doing so, you can reduce network load times and make your application work even when offline. Originally, it was created for service workers but in modern browsers the Cache API is available also in window, iframe, and worker contexts as-well. It’s a very powerful API that can improve drastically the application user experience.

Just like IndexedDB the Cache API storage is not limited and you can store hundreds of megabytes and even more if you need to. The API is asynchronous so it will not block your main thread. And it’s accessible through the global property caches.

To read more about the Cache API, the Google Chrome team has made a great tutorial.

Chris created an awesome Pen with a practical example of combining service workers and the Cache API.

Open Demo Bonus: Browser extension

If you build a browser extension, you have another option to store your data. I discovered it while working on my extension, daily.dev. It’s available via chrome.storage or browser.storage, if you use Mozilla’s polyfill. Make sure to request a storage permission in your manifest to get access.

There are two types of storage options, local and sync. The local storage is self-explanatory; it means it isn’t shared and kept locally. The sync storage is synced as part of the Google account and anywhere you install the extension with the same account this storage will be synced. Pretty cool feature if you ask me. Both have the same API so it’s super easy to switch back-and-forth, if needed. It’s async storage so it doesn’t block the main thread like localStorage. Unfortunately, I cannot create a demo for this storage option as it requires a browser extension but it’s pretty simple to use, and almost like localStorage. For more information about the exact implementation, refer to Chrome docs.

Conclusion

The browser has many options we can utilize to store our data. Following the Chrome team’s advice, our go-to storage should be IndexedDB. It’s async storage with enough space to store anything we want. localStorage is not encouraged, but is easier to use than IndexedDB. Cookies are a great way to share the client state with the server but are mostly used for authentication.

If you want to create pages with a shareable state such as a search page, use the URL’s query string to store this information. Lastly, if you build an extension, make sure to read about chrome.storage.

The post A Primer on the Different Types of Browser Storage appeared first on CSS-Tricks.

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

xm

Css Tricks - Wed, 10/21/2020 - 4:37am

This is a neat little HTML preprocessor from Giuseppe Gurgone. It has very few features, but one of them is HTML includes, which is something I continue to be baffled that HTML doesn’t support natively. There are loads of ways to handle it. I think it’s silly that it’s been consistently needed for decades and HTML could evolve to support it but hasn’t. So anyway, enter another option for handling it.

https://twitter.com/giuseppegurgone/status/1305851405660549122

What is extra neat is that it’s not just includes, but templating with includes in a really clean way. If this was Nunjucks, they solve that by creating a template.njk like…

{% block header %} This is the default (overridable) header. {% endblock %} <footer> {% block footer %} This is the default (overridable) footer. {% endblock %} </footer>

And then your actual pages use that template like…

{% extends "parent.html" %} {% block footer %} Special footer for this page. {% endblock %}

In xm, the syntax stays HTML-y, which is nice. So this template.html…

<slot name="header"></slot> <footer> <slot name="footer"></slot> </footer>

…gets used on a page like this:

<import src="template.html"> <fill name="header">Custom Header</fill> <fill name="footer"> <p>Custom footer</p> </fill> </import>

Very clean. The additional fact that you can arbitrarily chuck a <markdown> tag anywhere you want and use Markdown within it is extra handy.

The post xm appeared first on CSS-Tricks.

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

How to Think Like a Front-End Developer

Css Tricks - Tue, 10/20/2020 - 1:40pm

This is an extended version of my essay “When front-end means full-stack” which was published in the wonderful Increment magazine put out by Stripe. It’s also something of an evolution of a couple other of my essays, “The Great Divide” and “Ooops, I guess we’re full-stack developers now.”

The moment I fell in love with front-end development was when I discovered the style.css file in WordPress themes. That’s where all the magic was (is!) to me. I could (can!) change a handful of lines in there and totally change the look and feel of a website. It’s an incredible game to play.

Back when I was cowboy-coding over FTP. Although I definitely wasn’t using CSS grid!

By fiddling with HTML and CSS, I can change the way you feel about a bit of writing. I can make you feel more comfortable about buying tickets to an event. I can increase the chances you share something with your friends.

That was well before anybody paid me money to be a front-end developer, but even then I felt the intoxicating mix of stimuli that the job offers. Front-end development is this expressive art form, but often constrained by things like the need to directly communicate messaging and accomplish business goals.

Front-end development is at the intersection of art and logic. A cross of business and expression. Both left and right brain. A cocktail of design and nerdery.

I love it.

Looking back at the courses I chose from middle school through college, I bounced back and forth between computer-focused classes and art-focused classes, so I suppose it’s no surprise I found a way to do both as a career.

The term “Front-End Developer” is fairly well-defined and understood. For one, it’s a job title. I’ll bet some of you literally have business cards that say it on there, or some variation like: “Front-End Designer,” “UX Developer,” or “UI Engineer.” The debate around what those mean isn’t particularly interesting to me. I find that the roles are so varied from job-to-job and company-to-company that job titles will never be enough to describe things. Getting this job is more about demonstrating you know what you’re doing more than anything else¹.

Chris Coyier
Front-End Developer

The title variations are just nuance. The bigger picture is that as long as the job is building websites, front-enders are focused on the browser. Quite literally:

  • front-end = browsers
  • back-end = servers

Even as the job has changed over the decades, that distinction still largely holds.

As “browser people,” there are certain truths that come along for the ride. One is that there is a whole landscape of different browsers and, despite the best efforts of standards bodies, they still behave somewhat differently. Just today, as I write, I dealt with a bug where a date string I had from an API was in a format such that Firefox threw an error when I tried to use the .toISOString() JavaScript API on it, but was fine in Chrome. That’s just life as a front-end developer. That’s the job.

Even across that landscape of browsers, just on desktop computers, there is variance in how users use that browser. How big do they have the window open? Do they have dark mode activated on their operating system? How’s the color gamut on that monitor? What is the pixel density? How’s the bandwidth situation? Do they use a keyboard and mouse? One or the other? Neither? All those same questions apply to mobile devices too, where there is an equally if not more complicated browser landscape. And just wait until you take a hard look at HTML emails.

That’s a lot of unknowns, and the answers to developing for that unknown landscape is firmly in the hands of front-end developers.

Into the unknoooooowwwn. – Elsa

The most important aspect of the job? The people that use these browsers. That’s why we’re building things at all. These are the people I’m trying to impress with my mad CSS skills. These are the people I’m trying to get to buy my widget. Who all my business charts hinge upon. Who’s reaction can sway my emotions like yarn in the breeze. These users, who we put on a pedestal for good reason, have a much wider landscape than the browsers do. They speak different languages. They want different things. They are trying to solve different problems. They have different physical abilities. They have different levels of urgency. Again, helping them is firmly in the hands of front-end developers. There is very little in between the characters we type into our text editors and the users for whom we wish to serve.

Being a front-end developer puts us on the front lines between the thing we’re building and the people we’re building it for, and that’s a place some of us really enjoy being.

That’s some weighty stuff, isn’t it? I haven’t even mentioned React yet.

The “we care about the users” thing might feel a little precious. I’d think in a high functioning company, everyone would care about the users, from the CEO on down. It’s different, though. When we code a <button>, we’re quite literally putting a button into a browser window that users directly interact with. When we adjust a color, we’re adjusting exactly what our sighted users see when they see our work.

That’s not far off from a ceramic artist pulling a handle out of clay for a coffee cup. It’s applying craftsmanship to a digital experience. While a back-end developer might care deeply about the users of a site, they are, as Monica Dinculescu once told me in a conversation about this, “outsourcing that responsibility.”

We established that front-end developers are browser people. The job is making things work well in browsers. So we need to understand the languages browsers speak, namely: HTML, CSS, and JavaScript². And that’s not just me being some old school fundamentalist; it’s through a few decades of everyday front-end development work that knowing those base languages is vital to us doing a good job. Even when we don’t work directly with them (HTML might come from a template in another language, CSS might be produced from a preprocessor, JavaScript might be mostly written in the parlance of a framework), what goes the browser is ultimately HTML, CSS, and JavaScript, so that’s where debugging largely takes place and the ability of the browser is put to work.

CSS will always be my favorite and HTML feels like it needs the most love — but JavaScript is the one we really need to examine The last decade has seen JavaScript blossom from a language used for a handful of interactive effects to the predominant language used across the entire stack of web design and development. It’s possible to work on websites and writing nothing but JavaScript. A real sea change.

JavaScript is all-powerful in the browser. In a sense, it supersedes HTML and CSS, as there is nothing either of those languages can do that JavaScript cannot. HTML is parsed by the browser and turned into the DOM, which JavaScript can also entirely create and manipulate. CSS has its own model, the CSSOM, that applies styles to elements in the DOM, which JavaScript can also create and manipulate.

This isn’t quite fair though. HTML is the very first file that browsers parse before they do the rest of the work needed to build the site. That firstness is unique to HTML and a vital part of making websites fast.

In fact, if the HTML was the only file to come across the network, that should be enough to deliver the basic information and functionality of a site.

That philosophy is called Progressive Enhancement. I’m a fan, myself, but I don’t always adhere to it perfectly. For example, a <form> can be entirely functional in HTML, when it’s action attribute points to a URL where the form can be processed. Progressive Enhancement would have us build it that way. Then, when JavaScript executes, it takes over the submission and has the form submit via Ajax instead, which might be a nicer experience as the page won’t have to refresh. I like that. Taken further, any <button> outside a form is entirely useless without JavaScript, so in the spirit of Progressive Enhancement, I should wait until JavaScript executes to even put that button on the page at all (or at least reveal it). That’s the kind of thing where even those of us with the best intentions might not always toe the line perfectly. Just put the button in, Sam. Nobody is gonna die.

JavaScript’s all-powerfulness makes it an appealing target for those of us doing work on the web — particularly as JavaScript as a language has evolved to become even more powerful and ergonomic, and the frameworks that are built in JavaScript become even more-so. Back in 2015, it was already so clear that JavaScript was experiencing incredible growth in usage, Matt Mullenweg, co-founder of WordPress, gave the developer world homework: “Learn JavaScript Deeply”³. He couldn’t have been more right. Half a decade later, JavaScript has done a good job of taking over front-end development. Particularly if you look at front-end development jobs.

While the web almanac might show us that only 5% of the top-zillion sites use React compared to 85% including jQuery, those numbers are nearly flipped when looking around at front-end development job requirements.

I’m sure there are fancy economic reasons for all that, but jobs are as important and personal as it gets for people, so it very much matters.

So we’re browser people in a sea of JavaScript building things for people. If we take a look at the job at a practical day-to-day tasks level, it’s a bit like this:

  • Translate designs into code
  • Think in terms of responsive design, allowing us to design and build across the landscape of devices
  • Build systemically. Construct components and patterns, not one-offs.
  • Apply semantics to content
  • Consider accessibility
  • Worry about the performance of the site. Optimize everything. Reduce, reuse, recycle.

Just that first bullet point feels like a college degree to me. Taken together, all of those points certainly do.

This whole list is a bit abstract though, so let’s apply it to something we can look at. What if this website was our current project?

Our brains and fingers go wild!

  • Let’s build the layout with CSS grid. 
  • What fonts are those? Do we need to load them in their entirety or can we subset them? What happens as they load in? This layout feels like it will really suffer from font-shifting jank. 
  • There are some repeated patterns here. We should probably make a card design pattern. Every website needs a good card pattern. 
  • That’s a gorgeous color scheme. Are the colors mathematically related? Should we make variables to represent them individually or can we just alter a single hue as needed? Are we going to use custom properties in our CSS? Colors are just colors though, we might not need the cascading power of them just for this. Should we just use Sass variables? Are we going to use a CSS preprocessor at all?
  • The source order is tricky here. We need to order things so that they make sense for a screen reader user. We should have a meeting about what the expected order of content should be, even if we’re visually moving things around a bit with CSS grid.
  • The photographs here are beautifully shot. But some of them match the background color of the site… can we get away with alpha-transparent PNGs here? Those are always so big. Can any next-gen formats help us? Or should we try to match the background of a JPG with the background of the site seamlessly. Who’s writing the alt text for these?
  • There are some icons in use here. Inline SVG, right? Certainly SVG of some kind, not icon fonts, right? Should we build a whole icon system? I guess it depends on how we’re gonna be building this thing more broadly. Do we have a build system at all?
  • What’s the whole front-end plan here? Can I code this thing in vanilla HTML, CSS, and JavaScript? Well, I know I can, but what are the team expectations? Client expectations? Does it need to be a React thing because it’s part of some ecosystem of stuff that is already React? Or Vue or Svelte or whatever? Is there a CMS involved?
  • I’m glad the designer thought of not just the “desktop” and “mobile” sizes but also tackled an in-between size. Those are always awkward. There is no interactivity information here though. What should we do when that search field is focused? What gets revealed when that hamburger is tapped? Are we doing page-level transitions here?

I could go on and on. That’s how front-end developers think, at least in my experience and in talking with my peers.

A lot of those things have been our jobs forever though. We’ve been asking and answering these questions on every website we’ve built for as long as we’ve been doing it. There are different challenges on each site, which is great and keeps this job fun, but there is a lot of repetition too.

Allow me to get around to the title of this article. 

While we’ve been doing a lot of this stuff for ages, there is a whole pile of new stuff we’re starting to be expected to do, particularly if we’re talking about building the site with a modern JavaScript framework. All the modern frameworks, as much as they like to disagree about things, agree about one big thing: everything is a component. You nest and piece together components as needed. Even native JavaScript moves toward its own model of Web Components.

I like it, this idea of components. It allows you and your team to build the abstractions that make the most sense to you and what you are building.

Your Card component does all the stuff your card needs to do. Your Form component does forms how your website needs to do forms. But it’s a new concept to old developers like me. Components in JavaScript have taken hold in a way that components on the server-side never did. I’ve worked on many a WordPress website where the best I did was break templates into somewhat arbitrary include() statements. I’ve worked on Ruby on Rails sites with partials that take a handful of local variables. Those are useful for building re-usable parts, but they are a far cry from the robust component models that JavaScript frameworks offer us today.

All this custom component creation makes me a site-level architect in a way that I didn’t use to be. Here’s an example. Of course I have a Button component. Of course I have an Icon component. I’ll use them in my Card component. My Card component lives in a Grid component that lays them out and paginates them. The whole page is actually built from components. The Header component has a SearchBar component and a UserMenu component. The Sidebar component has a Navigation component and an Ad component. The whole page is just a special combination of components, which is probably based on the URL, assuming I’m all-in on building our front-end with JavaScript. So now I’m dealing with URLs myself, and I’m essentially the architect of the entire site. [Sweats profusely]

Like I told ya, a whole pile of new responsibility.

Components that are in charge of displaying content are almost certainly not hard-coded with data in them. They are built to be templates. They are built to accept data and construct themselves based on that data. In the olden days, when we were doing this kind of templating, the data has probably already arrived on the page we’re working on. In a JavaScript-powered app, it’s more likely that that data is fetched by JavaScript. Perhaps I’ll fetch it when the component renders. In a stack I’m working with right now, the front end is in React, the API is in GraphQL and we use Apollo Client to work with data. We use a special “hook” in the React components to run the queries to fetch the data we need, and another special hook when we need to change that data. Guess who does that work? Is it some other kind of developer that specializes in this data layer work? No, it’s become the domain of the front-end developer.

Speaking of data, there is all this other data that a website often has to deal with that doesn’t come from a database or API. It’s data that is really only relevant to the website at this moment in time.

  • Which tab is active right now?
  • Is this modal dialog open or closed?
  • Which bar of this accordion is expanded?
  • Is this message bar in an error state or warning state?
  • How many pages are you paginated in?
  • How far is the user scrolled down the page?

Front-end developers have been dealing with that kind of state for a long time, but it’s exactly this kind of state that has gotten us into trouble before. A modal dialog can be open with a simple modifier class like <div class="modal is-open"> and toggling that class is easy enough with .classList.toggle(".is-open"); But that’s a purely visual treatment. How does anything else on the page know if that modal is open or not? Does it ask the DOM? In a lot of jQuery-style apps of yore, yes, it would. In a sense, the DOM became the “source of truth” for our websites. There were all sorts of problems that stemmed from this architecture, ranging from a simple naming change destroying functionality in weirdly insidious ways, to hard-to-reason-about application logic making bug fixing a difficult proposition.

Front-end developers collectively thought: what if we dealt with state in a more considered way? State management, as a concept, became a thing. JavaScript frameworks themselves built the concept right in, and third-party libraries have paved and continue to pave the way. This is another example of expanding responsibility. Who architects state management? Who enforces it and implements it? It’s not some other role, it’s front-end developers.

There is expanding responsibility in the checklist of things to do, but there is also work to be done in piecing it all together. How much of this state can be handled at the individual component level and how much needs to be higher level? How much of this data can be gotten at the individual component level and how much should be percolated from above? Design itself comes into play. How much of the styling of this component should be scoped to itself, and how much should come from more global styles?

It’s no wonder that design systems have taken off in recent years. We’re building components anyway, so thinking of them systemically is a natural fit.

Let’s look at our design again:

A bunch of new thoughts can begin!

  • Assuming we’re using a JavaScript framework, which one? Why? 
  • Can we statically render this site, even if we’re building with a JavaScript framework? Or server-side render it? 
  • Where are those recipes coming from? Can we get a GraphQL API going so we can ask for whatever we need, whenever we need it?
  • Maybe we should pick a CMS that has an API that will facilitate the kind of front-end building we want to do. Perhaps a headless CMS?
  • What are we doing for routing? Is the framework we chose opinionated or unopinionated about stuff like this?

  • What are the components we need? A Card, Icon, SearchForm, SiteMenu, Img… can we scaffold these out? Should we start with some kind of design framework on top of the base framework?
  • What’s the client state we might need? Current search term, current tab, hamburger open or not, at least.
  • Is there a login system for this site or not? Are logged in users shown anything different? 
  • Is there are third-party componentry we can leverage here?
  • Maybe we can find one of those fancy image components that does blur-up loading and lazy loading and all that.

Those are all things that are in the domain of front-end developers these days, on top of everything that we already need to do. Executing the design, semantics, accessibility, performance… that’s all still there. You still need to be proficient in HTML, CSS, JavaScript, and how the browser works. Being a front-end developer requires a haystack of skills that grows and grows. It’s the natural outcome of the web getting bigger. More people use the web and internet access grows. The economy around the web grows. The capability of browsers grows. The expectations of what is possible on the web grows. There isn’t a lot shrinking going on around here.

We’ve already reached the point where most front-end developers don’t know the whole haystack of responsibilities. There are lots of developers still doing well for themselves being rather design-focused and excelling at creative and well-implemented HTML and CSS, even as job posts looking for that dwindle.

There are systems-focused developers and even entire agencies that specialize in helping other companies build and implement design systems. There are data-focused developers that feel most at home making the data flow throughout a website and getting hot and heavy with business logic. While all of those people might have “front-end developer” on their business card, their responsibilities and even expectations of their work might be quite different. It’s all good, we’ll find ways to talk about all this in time.

In fact, how we talk about building websites has changed a lot in the last decade. Some of my early introduction to web development was through WordPress. WordPress needs a web server to run, is written in PHP, and stores it’s data in a MySQL database. As much as WordPress has evolved, all that is still exactly the same. We talk about that “stack” with an acronym: LAMP, or Linux, Apache, MySQL and PHP. Note that literally everything in the entire stack consists of back-end technologies. As a front-end developer, nothing about LAMP is relevant to me.

But other stacks have come along since then. A popular stack was MEAN (Mongo, Express, Angular and Node). Notice how we’re starting to inch our way toward more front-end technologies? Angular is a JavaScript framework, so as this stack gained popularity, so too did talking about the front-end as an important part of the stack. Node and Express are both JavaScript as well, albeit the server-side variant.

The existence of Node is a huge part of this story. Node isn’t JavaScript-like, it’s quite literally JavaScript. It makes a front-end developer already skilled in JavaScript able to do server-side work without too much of a stretch.

“Serverless” is a much more modern tech buzzword, and what it’s largely talking about is running small bits of code on cloud servers. Most often, those small bits of code are in Node, and written by JavaScript developers. These days, a JavaScript-focused front-end developer might be writing their own serverless functions and essentially being their own back-end developer. They’ll think of themselves as full-stack developers, and they’ll be right.

Shawn Wang coined a term for a new stack this year: STAR or Design System, TypeScript, Apollo, and React. This is incredible to me, not just because I kind of like that stack, but because it’s a way of talking about the stack powering a website that is entirely front-end technologies. Quite a shift.

I apologize if I’ve made you feel a little anxious reading this. If you feel like you’re behind in understanding all this stuff, you aren’t alone.

In fact, I don’t think I’ve talked to a single developer who told me they felt entirely comfortable with the entire world of building websites. Everybody has weak spots or entire areas where they just don’t know the first dang thing. You not only can specialize, but specializing is a pretty good idea, and I think you will end up specializing to some degree whether you plan to or not. If you have the good fortune to plan, pick things that you like. You’ll do just fine.

The only constant in life is change.

– Heraclitus     – Motivational Poster         – Chris Coyier

¹ I’m a white dude, so that helps a bunch, too. ↩️
² Browsers speak a bunch more languages. HTTP, SVG, PNG… The more you know the more you can put to work! ↩️
³ It’s an interesting bit of irony that WordPress websites generally aren’t built with client-side JavaScript components. ↩️

The post How to Think Like a Front-End Developer appeared first on CSS-Tricks.

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

Smarter Ways to Generate a Deep Nested HTML Structure

Css Tricks - Tue, 10/20/2020 - 12:45pm

Let’s say we want to have the following HTML structure:

<div class='boo'> <div class='boo'> <div class='boo'> <div class='boo'> <div class='boo'></div> </div> </div> </div> </div>

That’s real a pain to write manually. And the reason why this post was born was being horrified on seeing it generated with Haml like this:

.boo .boo .boo .boo .boo

There were actually about twenty levels of nesting in the code I saw, but maybe some people are reading thing on a mobile phone, so let’s not fill the entire viewport with boos, even if Halloween is near.

As you can probably tell, manually writing out every level is far from ideal, especially when the HTML is generated by a preprocessor (or from JavaScript, or even a back-end language like PHP). I’m personally not a fan of deep nesting and I don’t use it much myself, but if you’re going for it anyway, then I think it’s worth doing in a manner that scales well and is easily maintainable.

So let’s first take a look at some better solutions for this base case and variations on it and then see some fun stuff done with this kind of deep nesting!

The base solution

What we need here is a recursive approach. For example, with Haml, the following bit of code does the trick:

- def nest(cls, n); - return '' unless n > 0; - "<div class='#{cls}'>#{nest(cls, n - 1)}</div>"; end = nest('&#x1f47b;', 5)

There’s an emoji class in there because we can and because this is just a fun little example. I definitely wouldn’t use emoji classes on an actual website, but in other situations, I like to have a bit of fun with the code I write.

We can also generate the HTML with Pug:

mixin nest(cls, n) div(class=cls) if --n +nest(cls, n) +nest('&#x1f47b;', 5)

Then there’s also the JavaScript option:

function nest(_parent, cls, n) { let _el = document.createElement('div'); if(--n) nest(_el, cls, n); _el.classList.add(cls); _parent.appendChild(_el) }; nest(document.body, '&#x1f47b;', 5)

With PHP, we can use something like this:

<?php function nest($cls, $n) { echo "<div class='$cls'>"; if(--$n > 0) nest($cls, $n); echo "</div>"; } nest('&#x1f47b;', 5); ?>

Note that the main difference between what each of these produce is related to formatting and white space. This means that targeting the innermost “boo” with .&#x1f47b;:empty is going to work for the Haml, JavaScript and PHP-generated HTML, but will fail for the Pug-generated one.

Adding level indicators

Let’s say we want each of our boos to have a level indicator as a custom property --i, which could then be used to give each of them a different background, for example.

You may be thinking that, if all we want is to change the hue, then we can do that with filter: hue-rotate() and do without level indicators. However, hue-rotate() doesn’t only affect the hue, but also the saturation and lightness. It also doesn’t provide the same level of control as using our own custom functions that depend on a level indicator, --i.

For example, this is something I used in a recent project in order to make background components smoothly change from level to level (the $c values are polynomial coefficients):

--sq: calc(var(--i)*var(--i)); /* square */ --cb: calc(var(--sq)*var(--i)); /* cube */ --hue: calc(#{$ch0} + #{$ch1}*var(--i) + #{$ch2}*var(--sq) + #{$ch3}*var(--cb)); --sat: calc((#{$cs0} + #{$cs1}*var(--i) + #{$cs2}*var(--sq) + #{$cs3}*var(--cb))*1%); --lum: calc((#{$cl0} + #{$cl1}*var(--i) + #{$cl2}*var(--sq) + #{$cl3}*var(--cb))*1%); background: hsl(var(--hue), var(--sat), var(--lum));

Tweaking the Pug to add level indicators looks as follows:

mixin nest(cls, n, i = 0) div(class=cls style=`--i: ${i}`) if ++i < n +nest(cls, n, i) +nest('&#x1f47b;', 5)

The Haml version is not too different either:

- def nest(cls, n, i = 0); - return '' unless i < n; - "<div class='#{cls}' style='--i: #{i}'>#{nest(cls, n, i + 1)}</div>"; end = nest('&#x1f47b;', 5)

With JavaScript, we have:

function nest(_parent, cls, n, i = 0) { let _el = document.createElement('div'); _el.style.setProperty('--i', i); if(++i < n) nest(_el, cls, n, i); _el.classList.add(cls); _parent.appendChild(_el) }; nest(document.body, '&#x1f47b;', 5)

And with PHP, the code looks like this:

<?php function nest($cls, $n, $i = 0) { echo "<div class='$cls' style='--i: $i'>"; if(++$i < $n) nest($cls, $n, $i); echo "</div>"; } nest('&#x1f47b;', 5); ?> A more tree-like structure

Let’s say we want each of our boos to have two boo children, for a structure that looks like this:

.boo .boo .boo .boo .boo .boo .boo .boo .boo .boo .boo .boo .boo .boo .boo

Fortunately, we don’t have to change our base Pug mixin much to get this (demo):

mixin nest(cls, n) div(class=cls) if --n +nest(cls, n) +nest(cls, n) +nest('&#x1f47b;', 5)

The same goes for the Haml version:

- def nest(cls, n); - return '' unless n > 0; - "<div class='#{cls}'>#{nest(cls, n - 1)}#{nest(cls, n - 1)}</div>"; end = nest('&#x1f47b;', 5)

The JavaScript version requires a bit more effort, but not too much:

function nest(_parent, cls, n) { let _el = document.createElement('div'); if(n > 1) { nest(_el, cls, n - 1); nest(_el, cls, n - 1) } _el.classList.add(cls); _parent.appendChild(_el) }; nest(document.body, '&#x1f47b;', 5)

With PHP, we only need to call the nest() function once more in the if block:

<?php function nest($cls, $n) { echo "<div class='$cls'>"; if(--$n > 0) { nest($cls, $n); nest($cls, $n); } echo "</div>"; } nest('&#x1f47b;', 5); ?> Styling the top level element differently

We could of course add a special .top (or .root or anything similar) class only for the top level, but I prefer leaving this to the CSS:

:not(.&#x1f47b;) > .&#x1f47b; { /* Top-level styles*/ } Watch out!

Some properties, such as transform, filter, clip-path, mask or opacity don’t only affect an element, but also also all of its descendants. Sometimes this is the desired effect and precisely the reason why nesting these elements is preferred to them being siblings.

However, other times it may not be what we want, and while it is possible to reverse the effects of transform and sometimes even filter, there’s nothing we can do about the others. We cannot, for example, set opacity: 1.25 on an element to compensate for its parent having opacity: .8.

Examples!

First off, we have this pure CSS dot loader I recently made for a CodePen challenge:

CodePen Embed Fallback

Here, the effects of the scaling transforms and of the animated rotations add up on the inner elements, as do the opacities.

Next up is this yin and yang dance, which uses the tree-like structure:

CodePen Embed Fallback

For every item, except the outermost one (:not(.☯️) > .☯️), the diameter is equal to half of that of its parent. For the innermost items (.☯️:empty, which I guess we can call the tree leaves), the background has two extra radial-gradient() layers. And just like the first demo, the effects of the animated rotations add up on the inner elements.

Another example would be these spinning candy tentacles:

CodePen Embed Fallback

Each of the concentric rings represents a level of nesting and combines the effects of the animated rotations from all of its ancestors with its own.

Finally, we have this triangular openings demo (note that it’s using individual transform properties like rotate and scale so the Experimental Web Platform features flag needs to be enabled in chrome://flags in order to see it working in Chromium browsers):

Triangular openings (live demo).

This uses a slightly modified version of the basic nesting mixin in order to also set a color on each level:

- let c = ['#b05574', '#f87e7b', '#fab87f', '#dcd1b4', '#5e9fa3']; - let n = c.length; mixin nest(cls, n) div(class=cls style=`color: ${c[--n]}`) if n +nest(cls, n) body(style=`background: ${c[0]}`) +nest('&#x1f53a;', n)

What gets animated here are the individual transform properties scale and rotate. This is done so that we can set different timing functions for them.

The post Smarter Ways to Generate a Deep Nested HTML Structure appeared first on CSS-Tricks.

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

Announcing the 2020 State of CSS Survey

Css Tricks - Tue, 10/20/2020 - 10:41am

Last year’s State of CSS Survey yielded interesting results. There’s the quick adoption of features, like calc() and CSS custom properties. There’s also the overwhelming opinion that CSS is fun to write even as we see a growing reliance on CSS-in JS. We also saw some predictable results, like the proliferation of VS Code as a preferred code editor, the dominance of flexbox as a layout model, as well as BEM and Sass being the most adopted technologies with the highest rates of satisfaction.

Chris and Dave disussed the 2019 State of CSS results with co-creator Sacha Greif on ShopTalk Show and dive into many, many more of the results and what they tell us about our industry.

But hey, it’s been [checking my calendar] slightly over a year since that survey and it’s back with a 2020 edition. If you can take it, please do — the more years we have on record, the more interesting trends we can find. Plus, we’ve got a whole bunch of new features and technologies to evaluate, like subgrid, user preference media queries, logical properties, line-clamp(), min(), max(), yada, yada, the list goes on!

And if nothing else, check out the survey site for some bonafide CSS tricks. &#x1f60e;

Direct Link to ArticlePermalink

The post Announcing the 2020 State of CSS Survey appeared first on CSS-Tricks.

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

“Durable”

Css Tricks - Tue, 10/20/2020 - 8:28am

Looks like the word “durable” is an emerging term in the world of serverless. As I understand it, it’s like allowing for state in places you wouldn’t normally expect to have it. For example, you call some cloud function and run some JavaScript… unless you have it go get some data from elsewhere, it has no information other than it’s own code. It doesn’t remember what happened last time it ran. It’s a clean slate each time. But let’s say your cloud function was a class, and when you initialized that class you got an ID, and through that ID you could talk to that exact instance of that class whenever you wanted. That instance sticks around as long as you need it. It’s durable.

Cloudflare released a feature called Durable Objects:

… we settled on “Unique Durable Objects”, or “Durable Objects” for short. Let me explain what they are by breaking that down:

Objects: Durable Objects are objects in the sense of Object-Oriented Programming. A Durable Object is an instance of a class — literally, a class definition written in JavaScript (or your language of choice). The class has methods which define its public interface. An object is an instance of this class, combining the code with some private state.

Unique: Each object has a globally-unique identifier. That object exists in only one location in the whole world at a time. Any Worker running anywhere in the world that knows the object’s ID can send messages to it. All those messages end up delivered to the same place.

Durable: Unlike a normal object in JavaScript, Durable Objects can have persistent state stored on disk. Each object’s durable state is private to it, which means not only that access to storage is fast, but the object can even safely maintain a consistent copy of the state in memory and operate on it with zero latency. The in-memory object will be shut down when idle and recreated later on-demand.

Pretty cool. The real-time aspects are extremely compelling.

Azure is also using “durable” in their offices through Durable Functions. Part of that offering is Entity Functions:

Entities behave a bit like tiny services that communicate via messages. Each entity has a unique identity and an internal state (if it exists). Like services or objects, entities perform operations when prompted to do so. When an operation executes, it might update the internal state of the entity. It might also call external services and wait for a response. Entities communicate with other entities, orchestrations, and clients by using messages that are implicitly sent via reliable queues.

The documentation is a little tricker for me to understand (I think it’s aimed at people who live and breath this stuff more than I do), but the concept sounds very similar to Cloudflare’s thing. Entities have IDs that you access them through. They persist and can be used for the same real-time-y stuff, like displaying the state/score of a video game to anyone who is connected.

The post “Durable” appeared first on CSS-Tricks.

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

Thidrekssaga I: Dietrich's youth

QuirksBlog - Tue, 10/20/2020 - 7:10am

I have been busy with my Thidrekssaga side project. Today I start a series that I call A First Reading, or a guided tour through the saga, with the first part: Dietrich’s youth.

I temporarily shelved technical considerations such as footnotes (which are really sidenotes) or a decent mobile view in favour of producing actual content. I enjoyed reading through the saga again and meeting old friends, although I may switch to technical stuff now just to give myself a varied diet.

Anyway, enjoy Dietrich’s youth. If you like it, we will need about twelve to fifteen of such articles to bring us to Dietrich’s death and the end of the saga.

WooCommerce Payments, Now with Support for Subscriptions and Saved Cards

Css Tricks - Tue, 10/20/2020 - 4:34am

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

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

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

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

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

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

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

Oh, and saved credit cards!

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

Heck yeah, checking out next time will be a breeze! All the things, all on WordPress

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

Try WooCommerce Payments

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

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

The failed promise of Web Components

Css Tricks - Mon, 10/19/2020 - 12:21pm

Lea has some words:

Perusing the components on webcomponents.org fills me with anxiety, and I’m perfectly comfortable writing JS — I write JS for a living! What hope do those who can’t write JS have? Using a custom element from the directory often needs to be preceded by a ritual of npm flugelhorn, import clownshoes, build quux, all completely unapologetically because “here is my truckload of dependencies, yeah, what”. Many steps are even omitted, likely because they are “obvious”.

When I wrote A Bit on Web Component Libraries, I was told the main thing I got wrong is that:

The idea was to make primitives that libraries could build on top of so they could ship less code. It was always the intention that you would use a library with them.

It was many years ago that HTML imports died. It was Dave’s pet peeve about Web Components for a long time. So I guess after that, it was a all-JavaScript-or-bust approach for Web Components. And I hate to say it, but it feels like it’s a lot closer to a bust than a boon.

I’m still optimistic though. Web Components can do some very cool stuff that only Web Components can do. The Shadow DOM being a big part of that. For example, I remember years ago Twitter experimented with making embedded Tweets into Web Components (instead of iframes) because it was way faster (in every way). That never manifested (&#x1f937;‍♂️), but it seemed like a damn fine idea to me.

I think the styling story is a big deal. I bet I’d reach for them at least slightly more if styling them wasn’t so weird. I saw Scott was asking about it just today and 75% of people wish there was a way to just reach into that Shadow DOM and style it from regular CSS. I get why that needs to be protected (that’s a huge point of the Shadow DOM in the first place), but having to very explicitly reach in seems like enough protection to me.

Direct Link to ArticlePermalink

The post The failed promise of Web Components appeared first on CSS-Tricks.

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

Our Best Posts on Web Components

Css Tricks - Mon, 10/19/2020 - 11:56am
Article Mar 18, 2019 An Introduction to Web Components Author Caleb Williams Article Mar 19, 2019 Crafting Reusable HTML Templates Author Caleb Williams Article Mar 22, 2019 Advanced Tooling for Web Components Author Caleb Williams Article Mar 20, 2019 Creating a Custom Element from Scratch Author Caleb Williams Article Jan 8, 2019 Styling a Web Component Author Chris Coyier Article Mar 21, 2019 Encapsulating Style and Structure with Shadow DOM Author Caleb Williams Article Jul 21, 2020 What ya need there is a bit of templating Author Chris Coyier Article Dec 27, 2017 ::part and ::theme, an ::explainer Author Robin Rendle Article Jul 28, 2020 A Bit on Web Component Libraries Author Chris Coyier Article Jul 20, 2017 Playing with Shadow DOM Author Chris Coyier Article Jun 9, 2017 An intro to web components with otters Author Chris Coyier Article Sep 7, 2018 Shadow DOM in Ionic Author Chris Coyier

A bit of backstory on why this page exists…

I made a fancy new Gutenberg block to insert posts into other posts, so this page is an example of using that (heavily) make a meta blog post about other blog posts. For the most part, topical pages like this are best served by tag pages. For example, our tag page for Web Components has more posts and is sortable in ways this is not. This is just a way to make a curated and hand-sorted grouping of posts, which is something we’ve done for a while with “Guide Collections”. But, we’re spinning down Guide Collections and redirecting them to tag pages and pages like this because they are easier to maintain.

The post Our Best Posts on Web Components appeared first on CSS-Tricks.

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

Syndicate content
©2003 - Present Akamai Design & Development.