Developer News

What I Like About Writing Styles with Svelte

Css Tricks - Wed, 10/23/2019 - 4:22am

There’s been a lot of well-deserved hype around Svelte recently, with the project accumulating over 24,000 GitHub stars. Arguably the simplest JavaScript framework out there, Svelte was written by Rich Harris, the developer behind Rollup. There’s a lot to like about Svelte (performance, built-in state management, writing proper markup rather than JSX), but the big draw for me has been its approach to CSS.

Single file components

??

React does not have an opinion about how styles are defined
—React Documentation?

?

????

A UI framework that doesn't have a built-in way to add styles to your components is unfinished.
—Rich Harris, creator of Svelte

?

In Svelte, you can write CSS in a stylesheet like you normally would on a typical project. You can also use CSS-in-JS solutions, like styled-components and Emotion, if you'd like. It’s become increasingly common to divide code into components, rather than by file type. React, for example, allows for the collocation of a components markup and JavaScript. In Svelte, this is taken one logical step further: the Javascript, markup and styling for a component can all exist together in a single `.svelte`? file. If you’ve ever used single file components in Vue, then Svelte will look familiar.

// button.svelte <style> button { border-radius: 0; background-color: aqua; } </style> <button> <slot/> </button> Styles are scoped by default

By default, styles defined within a Svelte file are scoped. Like CSS-in-JS libraries or CSS Modules, Svelte generates unique class names when it compiles to make sure the styles for one element never conflict with styles from another.

That means you can use simple element selectors like div and button in a Svelte component file without needing to work with class names. If we go back to the button styles in our earlier example, we know that a ruleset for <button> will only be applied to our <Button> component — not to any other HTML button elements within the page. If you were to have multiple buttons within a component and wanted to style them differently, you'd still need classes. Classes will also be scoped by Svelte.

The classes that Svelte generates look like gibberish because they are based on a hash of the component styles (e.g. svelte-433xyz). This is far easier than a naming convention like BEM. Admittedly though, the experience of looking at styles in DevTools is slightly worse as the class names lack meaning.

The markup of a Svelte component in DevTools.

It’s not an either/or situation. You can use Svelte’s scoped styling along with a regular stylesheet. I personally write component specific styles within .svelte files, but make use of utility classes defined in a stylesheet. For global styles to be available across an entire app — CSS custom properties, reusable CSS animations, utility classes, any ‘reset’ styles, or a CSS framework like Bootstrap — I suggest putting them in a stylesheet linked in the head of your HTML document.

It lets us create global styles

As we've just seen, you can use a regular stylesheet to define global styles. Should you need to define any global styles from within a Svelte component, you can do that too by using :global. This is essentially a way to opt out of scoping when and where you need to.

For example, a modal component may want to toggle a class to style the body element:

<style> :global(.noscroll) { overflow: hidden; } </style> Unused styles are flagged

Another benefit of Svelte is that it will alert you about any unused styles during compilation. In other words, it searches for places where styles are defined but never used in the markup.

Conditional classes are terse and effortless

If the JavaScript variable name and the class name is the same, the syntax is incredibly terse. In this example, I’m creating modifier props for a full-width button and a ghost button.

<script> export let big = false; export let ghost = false; </script> <style> .big { font-size: 20px; display: block; width: 100%; } .ghost { background-color: transparent; border: solid currentColor 2px; } </style> <button class:big class:ghost> <slot/> </button>

A class of ghost will be applied to the element when a ghost prop is used, and a class of big is applied when a big prop is used.

<script> import Button from './Button.svelte'; </script> <Button big ghost>Click Me</Button>

Svelte doesn’t require class names and prop names to be identical.

<script> export let primary = false; export let secondary = false; </script> <button class:c-btn--primary={primary} class:c-btn--secondary={secondary} class="c-btn"> <slot></slot> </button>

The above button component will always have a c-btn class but will include modifier classes only when the relevant prop is passed in, like this:

<Button primary>Click Me</Button>

That will generate this markup:

<button class="c-btn c-btn--primary">Click Me</button>

Any number of arbitrary classes can be passed to a component with a single prop:

<script> let class_name = ''; export { class_name as class }; </script> <button class="c-btn {class_name}"> <slot /> </button>

Then, classes can be used much the same way you would with HTML markup:

<Button class="mt40">Click Me</Button> From BEM to Svelte

Let's see how much easier Svelte makes writing styles compared to a standard CSS naming convention. Here's a simple component coded up using BEM.

.c-card { border-radius: 3px; border: solid 2px; } .c-card__title { text-transform: uppercase; } .c-card__text { color: gray; } .c-card--featured { border-color: gold; }

Using BEM, classes get long and ugly. In Svelte, things are a lot simpler.

<style> div { border-radius: 3px; border: solid 2px; } h2 { text-transform: uppercase; } p { color: gray; } .featured { border-color: gold; } </style> <div class:featured> <h2>{title}</h2> <p> <slot /> </p> </div> It plays well with preprocessors

CSS preprocessors feels a lot less necessary when working with Svelte, but they can work perfectly alongside one another by making use of a package called Svelte Preprocess. Support is available for Less, Stylus and PostCSS, but here we'll look at Sass. The first thing we need to do is to install some dependencies:

npm install -D svelte-preprocess node-sass

Then we need to import autoPreprocess in rollup.config.js at the top of the file.

import autoPreprocess from 'svelte-preprocess';

Next, let’s find the plugins array and add preprocess: autoPreprocess() to Svelte:

export default { plugins: [ svelte({ preprocess: autoPreprocess(), ...other stuff

Then all we need to do is specify that we’re using Sass when we’re working in a component file, using type="text/scss" or lang="scss" to the style tag.

<style type="text/scss"> $pink: rgb(200, 0, 220); p { color: black; span { color: $pink; } } </style> Dynamic values without a runtime

We’ve seen that Svelte comes with most of the benefits of CSS-in-JS out-of-the-box — but without external dependencies! However, there’s one thing that third-party libraries can do that Svelte simply can’t: use JavaScript variables in CSS.

The following code is not valid and will not work:

<script> export let cols = 4; </script> <style> ul { display: grid; width: 100%; grid-column-gap: 16px; grid-row-gap: 16px; grid-template-columns: repeat({cols}, 1fr); } </style> <ul> <slot /> </ul>

We can, however, achieve similar functionality by using CSS variables.

<script> export let cols = 4; </script> <style> ul { display: grid; width: 100%; grid-column-gap: 16px; grid-row-gap: 16px; grid-template-columns: repeat(var(--columns), 1fr); } </style> <ul style="--columns:{cols}"> <slot /> </ul>

I’ve written CSS in all kinds of different ways over the years: Sass, Shadow DOM, CSS-in-JS, BEM, atomic CSS and PostCSS. Svelte offers the most intuitive, approachable and user-friendly styling API. If you want to read more about this topic then check out the aptly titled The Zen of Just Writing CSS by Rich Harris.

The post What I Like About Writing Styles with Svelte appeared first on CSS-Tricks.

Digging Into the Preview Loading Animation in WordPress

Css Tricks - Tue, 10/22/2019 - 4:24am

WordPress shipped the Block Editor (aka Gutenberg) back in version 5.0 and with it came a snazzy new post preview screen that shows the WordPress logo drawing itself while the preview loads.

That's what you get when saving a post draft and clicking the "Preview" button in the editor. How'd they make it? I had a tough time viewing source for the page because the preview loads up pretty quickly, but I did see that SVG is being used for the WordPress logo. That's all I really needed because my mind instantly went back to something Chris wrote in 2014 that uses uses the stroke-dasharray and stroke-dashoffset properties to create the same effect.

This is the example Chris shared in that post:

See the Pen bGyoz by Chris Coyier (@chriscoyier) on CodePen.

I've since been able to get my hands on the CSS to confirm that the WordPress drawing is indeed using the same technique, but I'll share how my mind broke things out while I was trying to reverse-engineer it.

We're working with a straight-up inlined SVG

The neat thing about the WordPress version is that we're working with two SVG paths instead of one. That means we have two parts that appear to be drawing at the same time. Here's the SVG which is inlined in the HTML. We've got that "Generating preview" text as well, which can live outside the SVG.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" role="img" aria-hidden="true" focusable="false"> <path d="M48 12c19.9 0 36 16.1 36 36S67.9 84 48 84 12 67.9 12 48s16.1-36 36-36" fill="none"></path> <path d="M69.5 46.4c0-3.9-1.4-6.7-2.6-8.8-1.6-2.6-3.1-4.9-3.1-7.5 0-2.9 2.2-5.7 5.4-5.7h.4C63.9 19.2 56.4 16 48 16c-11.2 0-21 5.7-26.7 14.4h2.1c3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3L40 67.5l7-20.9L42 33c-1.7-.1-3.3-.3-3.3-.3-1.7-.1-1.5-2.7.2-2.6 0 0 5.3.4 8.4.4 3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3l11.5 34.3 3.3-10.4c1.6-4.5 2.4-7.8 2.4-10.5zM16.1 48c0 12.6 7.3 23.5 18 28.7L18.8 35c-1.7 4-2.7 8.4-2.7 13zm32.5 2.8L39 78.6c2.9.8 5.9 1.3 9 1.3 3.7 0 7.3-.6 10.6-1.8-.1-.1-.2-.3-.2-.4l-9.8-26.9zM76.2 36c0 3.2-.6 6.9-2.4 11.4L64 75.6c9.5-5.5 15.9-15.8 15.9-27.6 0-5.5-1.4-10.8-3.9-15.3.1 1 .2 2.1.2 3.3z" fill="none"></path> </svg> <p>Generating preview...</p>

The first path is an ellipse that acts as a border around the second path, which is the shape of the WordPress logo. It's probably a good idea to give each path a class — especially if this isn't the only element on the page — but I decided to leave things class-less since this is the only element in the demo. We can select both paths together in CSS or use pseudo-selectors (e.g. path:nth-child(2)) to select them individually in this instance.

There are a few other housekeeping things happening in there. For example, the SVG gets attributes to make it more accessible, such as identifying it as an image, hiding it from screen readers, and preventing it from being focused.

We need to lightly style the SVG

Very, very light styling. We need a stroke since there is no fill color on the paths. Otherwise we'll be looking at a whole lot of nothing. Well, an invisible shape, but essentially a nothing burger.

svg { stroke: #555; stroke-width: 0.5; width: 250px; }

That gives us the outline for both paths. The nice thing about the stroke-width property is that it accepts decimal values, so we get to make the lines a little thinner. The drawing sorta looks like it's drawn in pencil that way.

The width is pretty arbitrary here, but it's important because the stroke-dasharray and stroke-dashoffset properties we'll be working with rely on it. If those property values are smaller than the size of the SVG, then the drawing will stop short of completing. If it's too large, then the speed of the drawing becomes too fast.

Now that we know our width and can see the path strokes, we can set stroke-dasharray and stroke-dashoffset accordingly.

svg path { stroke-dasharray: 300; stroke-dashoffset: 300; }

A little larger than the SVG and lots of space between the dashes, which should be just about right. Those values can be adjusted to tailor the animation to your liking.

The rest is merely using Chris' technique

The drawing is a CSS animation using one keyframe. If we start the stroke-dashoffset at zero, then the paths will be invisible on initial load and grow to the 300 value we set earlier when the animation reaches 100%. Again, we set the offset at 300 so that the stroke dashes and the spaces between them will extend beyond the SVG to cover the entire thing.

All the magic is a mere five lines of code:

@keyframes draw { 0% { stroke-dashoffset: 0; } }

Name the animation whatever you'd like. We can get away with only defining the animation at 0% since 100% is implicit.

Oh! And we've gotta attach the animation to the paths, so:

svg path { animation: draw 2s ease-out infinite alternate; stroke-dasharray: 300; stroke-dashoffset: 300; }

You can definitely tweak those values as well to speed thing up or down. Easing gives the animation that slight pulsing effect where it starts and ends a little slower than the middle of the movement.

All together now!

See the Pen
WordPress Preview Loading State
by Geoff Graham (@geoffgraham)
on CodePen.

I mentioned it earlier, but I was eventually able to snatch the source code from the actual implementation and it's pretty darn close, using the same principles.

The post Digging Into the Preview Loading Animation in WordPress appeared first on CSS-Tricks.

Netlify Build Plugins Announcement

Css Tricks - Tue, 10/22/2019 - 3:25am

Netlify just dropped a new thing: Build Plugins. (It's in beta, so you have to request access for now.) Here's my crack at explaining it, which is heavily informed from David Well's announcement video.

You might think of Netlify as that service that makes it easy to sling up some static files from a repo and have a production site super fast. You aren't wrong. But let's step back and look at that. Netlify thinks about itself as a platform in three tiers:

  1. Netlify Build
  2. Netlify Dev
  3. Netlify Edge

Most of the stuff that Netlify does falls into those buckets. Connecting your Git repo and letting Netlify build and deploy the site? That's Build. Using Netlify's CLI to spin up the local dev environment and do stuff like test your local functions? That's Dev. The beefed-up CDN that actually runs our production sites? That's Edge. See the product page for that breakdown.

So even if you're just slapping up some files that come out of a static site generator, you're still likely taking advantage of all these layers. Build is taking care of the Git connection and possibly running a npm run build or something. You might run netlify dev locally to run your local dev server. And the live site is handled by Edge.

With this new Build Plugins release, Netlify is opening up access to how Build works. No longer is it just "connect to repo and run this command when the build runs." There is actually a whole lifecycle of things that happen during a build. This is how David described that lifecycle:

  1. Build Starts
  2. Cache is fetched
  3. Dependencies are installed
  4. Build commands are run
  5. Serverless Functions are built
  6. Cache is saved
  7. Deployment
  8. Post processing

What if you could hook into those lifecycle events and run your own code alongside them? That's the whole idea with Build Plugins. In fact, those lifecycle events are literally event hooks. Sarah Drasner listed them out with their official names in her intro blog post:

  • init: when the build starts
  • getCache: fetch the last build’s cache
  • install: when the project’s dependencies are installing
  • preBuild: runs directly before building the functions and running the build commands
  • functionsBuild: runs when the serverless functions are building, if they exist on the site
  • build: when the build commands are executing
  • package: package it to be deployed
  • preDeploy: runs before the built package is deployed
  • saveCache: save cached assets
  • finally: build finished, site deployed &#x1f680;

To use these hooks and run your own code during the build, you write a plugin (in Node JavaScript) and chuck it in a plugins folder at like ./plugins/myPlugin/index.js

function netlifyPlugin(config) { return { name: 'my-plugin-name', init: () => { console.log('Hi from init') }, } } module.exports = netlifyPlugin

...and adjust your Netlify config (file) to point to it. You're best off reading Sarah's post for the whole low-down and example.

Finished my first @Netlify build plugin. Now all I need is my pre-beta access to run a test.

KISS #jamstackconf pic.twitter.com/VIAnal1SpD

— Tony Alves (@3_Alves) October 17, 2019

OK. What's the point?

This is the crucial part, right? Kind of the only thing that matters. Having control is great and all, but it only matters if it's actually useful. So now that we can hook into parts of the build process on the platform itself, what can we make it do that makes our lives and sites better?

Here's some ideas I've gathered so far.

Sitemaps

David demoed having the build process build a sitemap. Sitemaps are great (for SEO), but I definitely don't need to be wasting time building them locally very often and they don't really need to be in my repo. Let the platform do it and put the file live as "a build artifact." You can do this for everything (e.g. my local build process needs to compile CSS and such, so I can actually work locally), but if production needs files that local doesn't, it's a good fit.

Notifications

Sarah demoed a plugin that hits a Twilio API to send a text message when a build completes. I do this same kind of thing having Buddy send a Slack message when this site's deployment is done. You can imagine how team communication can be facilitated by programmatic messaging like this.

Performance monitoring

Build time is a great time to get performance metrics. Netlify says they are working on a plugin to track your Lighthouse score between deployments. Why not run your SpeedCurve CLI thing or Build Tracker CLI there to see if you've broken your performance budget?

Performance expert @tkadlec wrote a Netlify Build Plugin for @SpeedCurve!
In this post, he breaks down how he our new private beta feature to create some perf tests for your site. Great writeup! https://t.co/aYU9NmosQQ pic.twitter.com/FnX6KgeLRG

— Netlify (@Netlify) October 22, 2019

Optimizations

Why not use the build time to run all your image optimizations? Image Optim has an API you could hit. SVGO works on the command line and Netlify says they are working on that plugin already. I'd think some of this you'd want to run in your local build process (e.g. drop image in folder, Gulp is watching, image gets optimized) but remember you can run netlify dev locally which will run your build steps locally, and you could also organize your Gulp such that the code that does image optimization can build part of a watch process or called explicitly during a build.

Images are a fantastic target for optimzation, but just about any resource can be optimized in some way!

I built a @Netlify build plugin to run subfont on your website. Seems like I don't have access to the build plugins myself yet, so I'd appreciate it if someone would try it out and give me feedback.https://t.co/PrnL65JSwb

— Peter Müller (@_munter_) October 18, 2019

Bailing out a problematic builds

If your build process fails, Netlify already won't deploy it. Clearly useful. But now you could trigger that failure yourself. What if that performance monitoring didn't just report on what is happening, but literally killed the build if a budget wasn't met? All you have to do is throw an error or process.exit, I hear.

Even more baller, how about fail a build on an accessibility regression? Netlify is working on an Axe plugin for audits.

Clearly you could bail if your unit tests (e.g. Jest) fail, or your end-to-end tests (e.g. Cypress) fail, meaning you could watch for 404's and all sorts of user-facing problems and prevent problematic deploys at all.

Use that build

Netlify is clearly all-in on this JAMstack concept. Some of it is pretty obvious. Chuck some static files on a killer CDN and the site has a wonderfully fast foundation. Some of it is less obvious. If you need server-powered code still, you still have it in the form of cloud functions, which are probably more powerful than most people realize. Some of it requires you to think about your site in a new way, like the fact that pre-building markup is not an all-or-nothing choice. You can build as much as you can, and leave client-side work to do things that are more practical for the client-side to do (e.g. personalized information). If you start thinking of your build process as this powerful and flexible tool to offload as much work as possible to, that's a great place to start.

The post Netlify Build Plugins Announcement appeared first on CSS-Tricks.

Why Parcel Has Become My Go-To Bundler for Development

Css Tricks - Mon, 10/21/2019 - 5:31am

Today we’re gonna talk about application bundlers — tools that simplify our lives as developers. At their core, bundlers pick your code from multiple files and put everything all together in one or more files in a logical order that are compiled and ready for use in a browser. Moreover, through different plugins and loaders, you can uglify the code, bundle up other kinds of assets (like CSS and images), use preprocessors, code-splitting, etc. They manage the development workflow.

There are lots of bundlers out there, like Browserify and webpack. While those are great options, I personally find them difficult to set up. Where do you start? This is especially true for beginners, where a "configuration file" might be a little scary.

That’s why I tend to reach for Parcel. I stumbled upon it accidentally while watching a tutorial on YouTube. The speaker was talking about tips for faster development and he heavily relied on Parcel as part of his workflow. I decided to give it a try myself.

What makes Parcel special

The thing I love the most about this bundler: it doesn’t need any configuration. Literally, none at all! Compare that to webpack where configuration can be strewn across several files all containing tons of code… that you may have picked up from other people’s configurations or inherited from other projects. Sure, configuration is only as complex as you make it, but even a modest workflow requires a set of plugins and options.

We all use different tools to simplify our job. There are things like preprocessors, post-processors, compilers, transpilers, etc. It takes time to set these up, and often a pretty decent amount of it. Wouldn’t you rather spend that time developing?

That’s why Parcel seems a good solution. Want to write your styles in SCSS or LESS? Do it! Want to use the latest JavaScript syntax? Included. Need a server for development? You got it. That’s barely scratching the surface of the large list of other features it supports.

Parcel allows you to simply start developing. That’s the biggest advantage of using it as a bundler — alongside its blazing fast compiling that utilizes multicore processing where other bundlers, including webpack, work off of complex and heavy transforms.

Where using Parcel makes sense

Parcel, like any tool, is not a golden pill that’s designed as a one-size-fits-all solution for everything. It has use cases where it shines most.

I’ve already mentioned how fast it is to get a project up and running. That makes it ideal when working with tight deadlines and prototypes, where time is precious and the goal is to get in the browser as quickly as possible.

That’s not to say it isn’t up to the task of handling complex applications or projects where lots of developers might be touching code. It’s very capable of that. However, I realize that those projects may very well benefit from a hand-rolled workflow.

It’s sort of like the difference between driving a car with an automatic transmission versus a stick shift. Sometimes you need the additional control and sometimes you don’t.

I’ve been working on a commercial multi-page website with a bunch of JavaScript under the hood, and Parcel is working out very well for me. It’s providing my server, it compiles my Sass to CSS, it adds vendor prefixes when needed, and it allows me to use import and export in my JavaScript files out of the box without any configuration. All of this allowed me to get my project up and running with ease.

Let’s create a simple site together using Parcel

Let’s take Parcel for a test drive to see how relatively simple it is to make something with it.

We’re going to build a simple page that uses Sass and a bit of JavaScript. We’ll fetch the current day of the week and a random image from Unsplash Source.

The basic structure

There's no scaffolding we’re required to use or framework needed to initialize our project. Instead, we’re going to make three files that ought to look super familiar: index.html, style.scss and index.js. You can set that up manually or in Terminal:

mkdir simple-site cd simple-site touch index.html && touch style.scss && touch index.js

Let’s sprinkle some boilerplate markup and the basic outline into our HTML file:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.scss"> <title>Parcel Tutorial</title> </head> <body> <div class="container"> <h1>Today is:</h1> <span class="today"></span> <h2>and the image of the day:</h2> <img src="https://source.unsplash.com/random/600x400" alt="unsplash random image"> </div> <script src="index.js"></script> </body> </html>

You may have noticed that I’m pulling in a web font (Lato) from Google, which is totally optional. Otherwise, all we’re doing is linking up the CSS and JavaScript files and dropping in the basic HTML that will display the day of the week and a link from Unsplash that will serve a random image. This is all we really need for our baseline.

Marvel at Parcel’s quick set up!

Let’s run the application using with Parcel as the bundler before we get into styling and scripts. Installing Parcel is like any thing:

npm install -g parcel-bundler # or yarn global add parcel-bundler

Let’s also create a package.json file should we need any development dependencies. This is also where Parcel will include anything it needs to work out of the box.

npm init -y # or yarn init -y

That’s it! No more configuration! We only need to tell Parcel which file is the entry point for the project so it knows where to point its server. That’s going to be our HTML file:

parcel index.html

If we open the console we’ll see something like this indicating that the server is already running:

Server running at http://localhost:1234

Parcel’s server supports hot reloading and rebuilds the app as change are saved.

Now, heading back to our project folder, we’ll see additional stuff,that Parcel created for us:

What’s important for us here is the dist folder, which contains all our compiled code, including source maps for CSS and JavaScript.

Now all we do is build!

Let’s go to style.scss and see how Parcel handles Sass. I’ve created variables to store some colors and a width for the container that holds our content:

$container-size: 768px; $bg: #000; $text: #fff; $primary-yellow: #f9f929;

Now for a little styling, including some nested rulesets. You can do your own thing, of course, but here’s what I cooked up for demo purposes:

*, *::after, *::before { box-sizing: border-box; } body { background: $bg; color: $text; font-family: 'Lato', sans-serif; margin: 0; padding: 0; } .container { margin: 0 auto; max-width: $container-size; text-align: center; h1 { display: inline-block; font-size: 36px; } span { color: $primary-yellow; font-size: 36px; margin-left: 10px; } }

Once we save, Parcel’s magic is triggered and everything compiles and reloads in the browser for us. No command needed because it’s already watching the files for changes.

This is what we’ve got so far:

The only thing left is to show the current day of the week. We’re going to use imports and exports so we get to see how Parcel allows us to use modern JavaScript.

Let’s create a file called today.js and include a function that reports the current day of the week from an array of days:

export function getDay() { const today = new Date(); const daysArr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; return daysArr[today.getDay()]; }

&#x1f4a1; It’s worth a note to remember that the getDay function returns Sunday as the first day of the week.

Notice we’re exporting the getDay function. Let’s go into our index.js file and import it there so it gets included when compiling happens:

import { getDay } from './today';

We can import/export files, because Parcel supports ES6 module syntax right out of the box — again, no configuration needed!

The only thing left is to select the <span> element and pass the value of the getDay function to it:

const day = document.querySelector('.today'); day.innerHTML = getDay();

Let’s see the final result:

Last thing is to build for production

We’ve created the app, but we want to serve it somewhere — whether it’s your personal server or some zero-configuration deployment like Surge or Now — and we want to serve compiled and minified code.

Here’s the one and only command we need:

parcel build index.js

This gives us all of the production-ready assets for the app. You can read more about Parcel’s product mode for some tips and tricks to get the most from your environment.

I’ve said it several times and I’ll say it again: Parcel is a great tool. It bundles, it compiles, it serves, it pre- and post-processes, it minifies and uglifies, and more. We may have looked at a pretty simple example, but hopefully you now have a decent feel for what Parcel offers and how you might start to use it in your own projects.

I’m interested if you’re already using Parcel and, if so, how you’ve been using it. Have you found it works better for some things more than others? Did you discover some neat trick that makes it even more powerful? Let me know in the comments!

The post Why Parcel Has Become My Go-To Bundler for Development appeared first on CSS-Tricks.

Designing accessible color systems

Css Tricks - Mon, 10/21/2019 - 5:30am

The team at Stripe explores how they’re refining their color palette to make it more accessible and legible for users across all their products and interfaces. Not only that but the team built a wonderful and yet entirely bonkers app for figuring out the ideal range of colors that they needed.

We built a web interface to allow us to visualize and manipulate our color system using perceptually uniform color models. The tool gave us an immediate feedback loop while we were iterating on our colors—we could see the effect of every change.

This tool is...whoa! I would love to learn a bit more about why they built this though as it looks like it wouldn’t have been a particularly quick and easy thing to put together. I wonder if that team has to support a wide-range of colors for their charts or data-visualization UI (as complex charts can often require a much larger range of colors for comparing bits of data effectively). Either way, this is pretty inspiring work.

This somewhat harkens to a couple of techniques for enforcing accessible colors, including one that uses custom properties with calc() and rgb by Josh Bader, and another by Facundo Corradini that also uses custom properties but with hsl with conditional statements.

Direct Link to ArticlePermalink

The post Designing accessible color systems appeared first on CSS-Tricks.

Options for Hosting Your Own Non-JavaScript-Based Analytics

Css Tricks - Fri, 10/18/2019 - 5:26am

There are loads of analytics platforms to help you track visitor and usage data on your sites. Perhaps most notably Google Analytics, which is widely used (including on this site), probably due to it's ease of integration, feature-richness, and the fact that it's free (until you need to jump up to the enterprise tier which is some crazy six-figure jump).

I don't take any particular issue with Google Analytics. In fact I quite like it, especially as I've learned more about customizing it, like we've done here on CSS-Tricks as well as on CodePen.

But there are other options. In particular, I wanted to look at some other options where:

I didn't find a sea of options to look at. The classic one I always think of in this category is Shaun Inman's Mint, but Mint isn't taking new customers anymore. Maybe I'm not looking in all the right places, and perhaps you can help with that. Please chime in with a comment if you know of more options — especially ones you have experience with.

Fathom Analytics

This is one Dave Rupert uses on his personal site and has written about. They have a paid hosted version, which is still focused on privacy in the sense that it does not track or store user data. But they also have a free self-hosted version you can run on your own. Actual data collection is done via a JavaScript snippet you put into your site.

I use @usefathom on Postgres with @HasuraHQ to get my stats through GraphQL on my @gatsbyjs powered blog https://t.co/fKotgYuHFG (generates the “most views” list in the footer).

— knut (@kmelve) September 9, 2019

Ackee

This is based on Node.js and can only be self-hosted. Actual data collection is done with a JavaScript snippet you put into the site.

Matomo On-Premise

Matomo Cloud is their hosted version, and On-Premisis is the self-hosted version. The actual data collection is done via a JavaScript snippet you put into the site.

I personally use matomo for my side projects. Its vast and getten me fall into love. ✌

— RaKesh Mandal (@rkalways_) September 10, 2019

GoAccess

GoAccess is notable because it's the first in the list that is a "web log analyzer" which means it looks at access logs that your web server creates rather than relying on JavaScript reporting from the client side. Theoretically, this should be more accurate since client-side JavaScript can be blocked. GoAccess generates reporting that can be viewed in the terminal, as well as browser-based charts and graphs.

I use GoAccess as a static site generated on a cronjob (https://t.co/yiQMev7NDu) which seems to work quite nicely for very basic site. Doesn’t (afaik) handle ignoring spiders etc

— Shane Hudson (@ShaneHudson) September 9, 2019

Netlify Analytics

Netlify Analytics isn't self-hosted in that you install it yourself on servers you rent. A big point of using Netlify is that it prevents you from dealing with your own servers. The analytics are server-log based rather than JavaScript which can be desirable as they are likely more accurate and don't impact performance.

Web hosts are uniquely qualified to offer analytics to their users as they configure their own logging and such. For example, I also have analytics on this site through Flywheel, without installing anything, because they can analyze the traffic going through their servers. We wrote up an overview of the service when it was released. AWStats

AWStats is the oldest analytics tool on the block. When I started out on the web, all the web hosting providers touted AWStats dashboards as part of their offerings. It runs on Perl, and like the last two services above, it gets data from server logs.

It ain't pretty but it's free, open-source, and has the stability of being a software project nearly 20 years old.

The post Options for Hosting Your Own Non-JavaScript-Based Analytics appeared first on CSS-Tricks.

Laying the Foundations

Css Tricks - Fri, 10/18/2019 - 5:22am

Here’s a new book by Andrew Couldwell all about design systems and I'm looking forward to reading the book because it looks like his experience will offer a bunch of insightful thoughts and advice.

From the book's description:

This is real talk about creating design systems and digital brand guidelines. No jargon, no glossing over the hard realities, and no company hat. Just good advice, experience, and practical tips.

System design is not a scary thing — this book aims to dispel that myth. It covers what design systems are, why they are important, and how to get stakeholder buy-in to create one. It introduces you to a simple model, and two very different approaches to creating a design system. What's unique about this book is its focus on the importance of brand in design systems and creating documentation. It’s a comprehensive, practical guide that’s simple to follow and easy on the eye.

Direct Link to ArticlePermalink

The post Laying the Foundations appeared first on CSS-Tricks.

JAMstack Tools and The Spectrum of Classification

Css Tricks - Thu, 10/17/2019 - 6:46am

With the wonderful world of JAMstack getting big, all the categories of services and tools that help it along are as important as ever. There are static site generators, headless CMSs, and static file hosts.

I think those classifications are handy, and help conversations along. But there is a point where nuance is necessary and these classification buckets get a little leaky.

Note, these charts are just intended to paint a spectrum, not to be a comprehensive list of services.

Headless CMSs

A Headless CMS is a CMS that provides an admin area for creating and editing content, but offers no front-end to build the website from. All the content is accessed via APIs.

Imagine WordPress, which has an admin area, but it also has themes from which you build the website from on the server-side, with all kinds of PHP functions for you to use the content data. All that theming stuff is the "head". So a headless CMS would be like WordPress with just the admin area. And indeed you can use it that way, as it offers APIs.

There is even more nuance here, as there are services that offer an admin area, but don't actually store the data for you. Plus there is CMSs that are hosted for you, and CMSs where you have to bring your own hosting. Let's have a peak.

Service Headless? Hosting Notes Contentful Yes Cloud A classic headless CMS Sanity JSON data structure, accessed via APIs, custom admin area is self-hosted Cockpit Self Comes with admin UI Strapi KeystoneJS All code, not even an admin UI WordPress Sorta – Usually used with head Self or Cloud Has a head, but you don't have to use it, you choose to only use APIs to access content if you wish. Drupal Self CraftCMS Self Specifically has a headless mode and GraphQL API. Craft Cloud will bring a cloud-hosted headless varient NetlifyCMS Sorta - Doesn't actually store content, just helps edit it. GUI for Git-hosted Markdown Forestry Cloud Joomla No Self A classic headed CMS Squarespace Cloud Site builder, meant to build hosted/headed sites Wix Static Site Hosts

This is tricky to talk about because literally, any web host will host static files, and probably do an OK job of it. I think it's most useful to consider hosts that only do static hosting on purpose because it means they can optimize for that situation do other useful things.

Service Notes Netlify The gold standard in static file hosts right now. Developer conviences galore. Cloudflare Workers Sites CDN-first static file hosting alongside a cloud functions service. Firebase Hosting Firebase is a whole suite of sub-products, but the hosting in particular is static and on a CDN. GitHub Pages Static file host, but will also run Jekyll and other actions. Is not a CDN. Neocities Static file host with online editor and community. S3 Raw file storage. Can be configured to be a web host. Not a CDN unless you put CloudFront in front of it. Bluehost Not really a static file host. MediaTemple Hostgator

Sometimes you'll see people trying to use stuff like Dropbox or Google Drive to do static file hosting (for a website), but I've found these services generally ultimately don't like that and prevent the use for that. If it works today, fine, but I wouldn't count on any of them long term.

Static Site Generators

You would think this category would be straightforward, without much spectrum. A static site generator takes input and makes statically generated pages that can render without, say, needing to hit a database. But even here there is a spectrum.

The language the generator is in kinda matters. It affects speed. It affects installability on different local platforms. It affects your ability to write code to extend it and hack on it.

But perhaps more importantly, not all static site generators are only static site generators. Some can be run on the server as well, weirdly enough. And there are some that kinda look like static site generators, but are more correctly classified as flat-file CMSs.

Software Lang Notes Jekyll Ruby One of the originals in this generation of static site generator. Hugo Go Known for speed. 11ty Node Processes 11 different template languages out of the box. Gatsby React Gatsby is truly a static site generator, but generally, the sites "hydrate" into SPAs, but remain static (nothing server-rendered). Big ecosystem of plugins to help with connecting data sources, handling images, etc. Next Next can do static site generation, but it can also run live in Node and do server-side rendering on the fly ("Isomorphic JavaScript"). Nuxt Vue Nuxt is the spirtiual companion to Next but in Vue. It also can either be staticly generator or run isomorphicly. Kirby PHP Kirby runs from static files (no database), but isn't really a static site as the pages are rendered by PHP. Statamic Statamic is similar to Kirby in that static files are used for data but the page themselves are rendered by PHP. Perch Just an example of a CMS that keeps data in a database and isn't trying to be a static site generator at all.

The post JAMstack Tools and The Spectrum of Classification appeared first on CSS-Tricks.

Weekly Platform News: CSS column-span Property, ADA applies to Websites, Auto-generated Image Descriptions

Css Tricks - Thu, 10/17/2019 - 5:17am

In this week's roundup: multi-column layouts gain wide support, the ADA means more A11y for retailers, and Google is doing something about all the empty image alt attributes in the wild.

The CSS column-span property will soon be widely supported

The CSS column-span property, which has been supported in Chrome and Safari since 2010 (and IE since 2012), is finally coming to Firefox in version 71 (in December).

This feature enables elements that span across all columns in a multiple-column layout. In the following demo, the headings span across both columns.

article { column-count: 2; } h2 { column-span: all; }

See the Pen
Demo of CSS column-span: all
by Šime Vidas (@simevidas)
on CodePen.

(via Ting-Yu Lin)

The Americans with Disabilities Act applies to websites

In the United States, the Americans with Disabilities Act (ADA) applies to websites, which means that people can sue retailers if their websites are not accessible.

Domino’s Pizza’s appeal was recently turned down by the Supreme Court, so the lawsuit against them for failing to make their website accessible to screen reader users will now resume in district court.

Guillermo Robles, who is blind, filed suit in Los Angeles three years ago and complained he had been unable to order a pizza online because the Domino’s website lacked the software that would allow him to communicate. He cited the ADA, which guarantees to people with a disability “full and equal enjoyment of the goods and services ... of any place of public accommodations.”

(via David G. Savage)

Google announces automatically generated image descriptions for Chrome

When used with the VoiceOver screen reader, Chrome can now automatically generate image descriptions for images that do not have proper alt text (<img alt> attribute). Google has already created more than 10 million image descriptions, but they are not meant to replace alt text written by humans.

Image descriptions automatically generated by a computer aren’t as good as those written by a human who can include additional context, but they can be accurate and helpful.

This new accessibility feature, called “Accessibility Image Descriptions,” may not be enabled by default in your version of Chrome, but you can enable it manually on the chrome://flags page.

(via Dominic Mazzoni)

More news...

Read even more news in my weekly Sunday issue that can be delivered to you via email every Monday morning.

More News ?

The post Weekly Platform News: CSS column-span Property, ADA applies to Websites, Auto-generated Image Descriptions appeared first on CSS-Tricks.

Making Tables Responsive With Minimal CSS

Css Tricks - Thu, 10/17/2019 - 4:23am

Here’s a fabulous CSS trick from Bradley Taunt in which he shows how to make tables work on mobile with just a little bit of extra code. He styles each table row into a card that looks something like this:

See the Pen
Responsive Tables #2.5: Flexbox
by Bradley Taunt (@bradleytaunt)
on CodePen.

(Make sure to grab the Pen and make it a bit smaller to see how the design works responsively.)

Bradley’s example markup looks like this – clean, accessible, regular ol’ HTML:

<table> <thead> <tr> <th>Type of Food</th> <th>Calories</th> <th>Tasty Factor</th> </tr> </thead> <tbody> <tr> <td><span>Type of Food</span> Slice of Pizza</td> <td><span>Calories</span> 450</td> <td><span>Tasty Factor</span> 95%</td> </tr> </tbody> </table>

How does he make that card effect? He uses flexbox on smaller screens and sets the span elements to reveal themselves.

However! I’m not a big fan of those spans. They’re hidden on larger screen sizes but the markup is still there, so it doesn’t feel particularly clean to me. I was working on a project a little while ago where we stumbled on the same problem. We decided to use data attributes on each td instead, like this:

<table> <thead> <tr> <th>Type of Food</th> <th>Calories</th> <th>Tasty Factor</th> </tr> </thead> <tbody> <tr> <td data-title="Type of Food">Slice of Pizza</td> <td data-title="Calories">450</td> <td data-title="Tasty Factor">95%</td> </tr> </tbody> </table>

Then we can grab that data attribute in our styles and render it on the page in a pseudo element:

td:before { content: attr(data-title); }

From there we absolutely position the pseudo element to the side and only show it on smaller screens with a media query. I’m uncertain about the accessibility implications of this but it just feels a bit easier to read and understand in my opinion.

Either way, I think this post is a great reminder about all the tricky issues that pop up once you start using tables. There’s so many ways to handle things responsively and those decisions should entirely be made on the context of the design.

Responsive tables...

When you need to compare data up and down columns, it's probably best to largely leave the table structure alone and allow scrolling.

If each row can be broken apart and still be useful, collapsing them to avoid scrolling is nice.https://t.co/zeMFdrwU1M pic.twitter.com/3z8hQDvNAZ

— CSS-Tricks (@css) October 11, 2019

Direct Link to ArticlePermalink

The post Making Tables Responsive With Minimal CSS appeared first on CSS-Tricks.

Get the Complete Intro to Web Development and Intro to React (with Hooks!) with Brian Holt ????

Css Tricks - Thu, 10/17/2019 - 4:22am

(This is a sponsored post.)

Hey, Marc here from Frontend Masters — excited to support CSS-Tricks ❤️!

Have you checked out Brian Holt's courses yet? His most popular courses are the "Complete Intro" courses which give you the lay of the land in Web Development as well as the entire React ecosystem.

Complete Intro to Web Development, v2

This Complete Intro to Web Development assumes no prior coding knowledge, taking you from not knowing how websites are made to writing code for your own sites in HTML, CSS, JavaScript…all the way to building a server with Node.js!

You’ll learn to...

  • Setup the tools you need to write code.
  • Write HTML and CSS to put content on a websites and make them look aesthetically pleasing.
  • Make websites interactive with JavaScript, the de facto programming language of the web.
  • Use Git and other modern development tools through your computer’s terminal to save your work and pull in code libraries.
  • Use JavaScript via Node.js to serve your own website from a server.
Complete Intro to React, v5

In the Complete Intro to React course, you’ll start from the ground up, getting all the way to using the latest features in React, including hooks, effects, context, and portals. Throughout the course, you’ll piece together tools from the entire React ecosystem (like Reach Router) to build a full application to browse adoptable pets.

You’ll learn to...


  • Use the new hooks and effects methods to handle state in function components.

  • Understand how React works by writing React with and without JSX.

  • Package client-side applications with Parcel.

  • Leverage Prettier and ESLint to maintain high-quality code.

  • Route to pages and search results with Reach Router.


  • Grab API data and update state asynchronously in an effect.
Intermediate React, v2

The Intermediate React, v2 course is a modular course where you can pick and choose the various pieces of the react ecosystem you want to learn.

You'll learn to...


  • Learn all the types of hooks, including useReducer, useCallback, useRef and more.

  • Make CSS local to your JavaScript components using the Emotion library.

  • Load your apps fast using code splitting, Suspense React and server-side rendering.

  • Use TypeScript for writing scalable apps with superior developer experience.

  • Redux for state management

  • Test your React applications using Jest.

You'll love Brian's awesome courses!

Join Now

Direct Link to ArticlePermalink

The post Get the Complete Intro to Web Development and Intro to React (with Hooks!) with Brian Holt &#x1f3a3; appeared first on CSS-Tricks.

The `hidden` Attribute is Visibly Weak

Css Tricks - Wed, 10/16/2019 - 11:07am

There is an HTML attribute that does exactly what you think it should do:

<div>I'm visible</div> <div hidden>I'm hidden</div>

It even has great browser support. Is it useful? Uhm. Maybe. Not really.

Adam Laki likes the semantics of it:

If we use the hidden attribute, we make our semantic a little better. Anybody will understand what does a “hidden” attribute means on an element.

Monica Dinculescu calls it a lie:

the hidden rule is a User Agent style, which means it's less specific than a moderate sneeze. This means that your favourite display style will override it:

<style> div { display: block; } </style> <div hidden> lol guess who's not hidden anymore hint: it's this thing </div>

So two related problems...

  1. It's extremely weak. Literally any change to the display property other than the none value on the element with any strength selector will override it. Much like any other display property, like width or whatever, except the it feels somehow worse to have a hidden attribute actively on an element and have it not actually be hidden.
  2. The display property is sadly overloaded with responsibility. It would be way cool if hidden was a CSS property that could be in charge of the visibility/access of elements rather than the same property that controls the type of block it is. But alas, backward compatibility 4-lyfe of the web stops that (which is a good thing for the health of the web overall).

If you really love the semantics of the attribute, Monica suggests:

[hidden] { display: none !important; }

Seems like a nice addition to any "reset" or base stylesheet.

Otherwise, the classic technique of hiding things with a class is absolutely fine. I typically have a utility class:

.hide, .hidden { display: none; }

But remember there are always a million ways to do things. I find myself regularly doing one-off hide/show mechanisms. For example, a menu that you need to toggle the visibility of with flair, but remain accessible at all times...

.menu { opacity: 0; visibility: hidden; transition: 0.2s; transform: translateX(20px); &[data-open] { opacity: 1; visibility: visible; transform: translateX(0); } }

The post The `hidden` Attribute is Visibly Weak appeared first on CSS-Tricks.

Workflow Considerations for Using an Image Management Service

Css Tricks - Wed, 10/16/2019 - 5:06am

There are all these sites out there that want to help you with your images. They do things like optimize your images and help you serve them performantly.

Here's the type of service I mean.

That's a very good thing. By any metric, images are a major slice of the resources on websites, and we're notoriously bad at optimizing them and doing all the things we could to lower the performance hit from them. I'm sitting at a conference right now and Dave just bet everyone in the audience $100 that he could find an unoptimized image on their site. I wasn't about to take him up on it.

So you use some service to help you deliver images better. Smart. Many of them will make managing and optimizing images a lot easier. But I don't consider them a no-brainer. There is a lot to think about, like making choices that don't paint you into a corner.

I should be able to upload images from my own CMS.

I don't want to go to your site to upload my assets. I want to use the media management in my own CMS. So, the service should have an API at a minimum, and possible even officially maintained CMS plugins.

This site uses WordPress. I can drag and drop images into the media library and posts very easily. I can search my media library for images I've uploaded before. I like that, and I want to take advantage of it today, and as it evolves.

The images should be uploaded to my own server.

If it also has to be uploaded to the image service, that's fine. But it should go to my server first, then to the service. That way, I still maintain ownership of the source file.

Images within content should use functional, semantic markup in my CMS.

I'd prefer that the images within content are stored as totally functional HTML in my database:

<img src="/images/flower.jpg" alt="a blue flower">

It could be fancier than that, like using srcset (but probably not sizes as that will change as the design changes), or be contained within <picture> or <figure> elements... whatever you like that makes sense as semantic HTML. The most important thing being that the content in my database has fully functional HTML with a src on the image that points to a real image on my real server.

The implementation of the image service will involve filtering that HTML to do whatever it needs to do, like replace the URLs to generate fancier responsive image markup and whatnot.

Between having functional HTML and images on my server, that enables me to turn off the image service if I need to. Services have a habit of coming and going, or changing in ways that make them more or less palatable. I don't want to be locked-in; I want freedom. I want to be able turn off the service and have a perfectly functional site with perfectly functional images, and not be obstructed from moving to a different service — or no service at all.

Even if I didn't use the service in the past, I want all my images to benefit from it.

I just mentioned filtering the HTML for images in my database. That should happen for all the images on my site, even if they were uploaded and used before I started using the image service.

This probably means the services offers a URL-based "get" API to optimize images on-the-fly pulled from their canonical locations.

I shouldn't have to think about format or size.

I want to upload whatever I have. Probably some huge un-optimized screenshot I just took. If I think about it at all, I want to upload something much too big and much too high-quality so that I know I have a great original version available. The service will create optimized, sized, and formatted images as needed.

I also want to upload SVG and have it stay SVG (that's also optimized).

The images will ultimately be served on a CDN.

CDNs are vital for speed. Australians get images from servers hosted in Australia. Canadians get images from servers hosted in Canada. The servers are configured to be fast and cookie-less and all the fancy over-my-head things that make an asset CDN scream.

The images should serve in the right format.

If you serve images in WebP format to browsers that support it, you'll probably get as much or more performance out of that optimization than serving re-sized images with responsive images syntax. It's a big deal.

I want the service to know what the best possible format for any particular image for any particular browser and serve the image in that format. This is going to change over time, so I want the service to stay on top of this so I don't have to.

I know that involved formats like JPEG-XR and JPEG-2000 three years ago. Is that still the case? I have no idea. This is a core value proposition for the service.

It should optimize the images and handle quality.

This is perhaps the most obvious feature and the reason you reach for an image service in the first place. Images need optimization. There are perhaps dozens of image optimization tools/algorithms that aim to squeeze every last byte out of images. The image service probably uses those or even has its own fancy tech for it. Ideally, the default is to optimize an image the most it possibly can be without noticeably hurting the quality, but still allowing me to ratchet it down even more if I want to.

Don't shame me for using high-pixel density images.

A lot of image services have some sort of tester tool where you drop in a URL and it tells you how bad you're doing with images. Many of them test the size of the image on the rendered page and compare the dimensions of the original image. If the original image is larger, they tell you could have had savings by sizing it down. That's obnoxious to me. High-pixel density displays have been around for a long time and it's no crime to serve them.

It should help me serve the right size for the device it's on and the perfect responsive syntax if needed.

Not all images benefit from the same responsive breakpoints. Check out the site Responsive Image Breakpoints. It generates versions of the image that are best depending on the image itself. That's the kind of help I like to see from an image service. Take something hard and automate it for me.

I know I'll probably need to bring my own sizes attribute because that is very dependant on my own CSS and how the design of the site plays out. It's still important, and makes me wonder if an image service could step up and help me figure out what my optimal sizes attribute should be for certain images. Like loading my site at different sizes and seeing how large the image renders with my CSS and calculating it from there to use later.

Just me.

This is just my own list of requirements. I feel like it's fairly reflective of "normal" sites that have a bunch of images and want to do the right thing to serve them.

I didn't go into all the fancy features image services offer, like being able to tell you that an image contains a giraffe facing west and hasn't eaten since Thursday while offering to recolor its retinas. I know those things are vital to some companies. This is more about what seems to me the widest and most common use case of just hosting and delivering images in the best way current technology allows.

The post Workflow Considerations for Using an Image Management Service appeared first on CSS-Tricks.

Ten-Ton Widgets

Css Tricks - Tue, 10/15/2019 - 9:59am

At a recent conference talk (sorry, I forget which one), there was a quick example of poor web performance in the form of a third-party widget. The example showed a site that installed the widget in order to add a "email us" button fixed to the bottom right of the viewport. Not even a live-chat widget — just an email thing. It weighed in at something like 470KB, which is straight bananas.

Just in case you are someone who feels trapped into using a ten-ton widget because you aren't yet sure how to replicate the same functionality, I've prepared a small chunk of HTML for you.

It's 602 Bytes, or about 1/10th of 1% of the size of that other widget — with nothing to download, parse or render block.

See the Pen
Mailto Fixed Postion Widget
by Chris Coyier (@chriscoyier)
on CodePen.

Perhaps on your own site, you'd move the styles out to your stylesheet and add in some hover and focus styles.

It's not that third-party JavaScript has to be bad. It just has a habit of being bad.

My friend Richard showed me a new product he built called Surfacer. It's like an RSS widget that you can put anywhere.

See the Pen
Surfacer
by Chris Coyier (@chriscoyier)
on CodePen.

That's a 773 Byte JavaScript file that does a 3.5KB Ajax request for data, and you'd place it at the end of the document to avoid any render-blocking. It would be nice to see more of this kind of thing.

The post Ten-Ton Widgets appeared first on CSS-Tricks.

Let’s Make a Fancy, but Uncomplicated Page Loader

Css Tricks - Tue, 10/15/2019 - 4:06am

It’s pretty common to see a loading state on sites these days, particularly as progressive web apps and reactive sites are on the rise. It’s one way to improve "perceived" performance — that is, making it feel as though the site is loading faster than it actually is.

There’s no shortage of ways to make a loader — all it takes is a quick search on CodePen to see oodles of examples, from animated GIFs to complex animations. While it’s tempting to build the fanciest of the fancy loaders, we can actually do a pretty darn good job with only a minimal amount of CSS and JavaScript.

Here’s an example we can make together.

See the Pen
Preloader with JavaScript FadeOut
by Maks Akymenko (@maximakymenko)
on CodePen.

SVG and CSS is all we need for the spinner

I’m going to assume that you’ve already created a project, so we’ll jump right in and start with the spinner — or "pre-loader" as it is also called.

SVG is a great option for a spinner. It’s scalable and implementing it is as easy as an image tag. We could make one from scratch, say in an image editor like Illustrator, Sketch or Figma. For this example, I’m just going to grab this one from loading.io, which is a nice resource to make and customize different loaders.

Now that we have an SVG for the visual, we can drop it into HTML:

<div class="preloader"> <img src="spinner.svg" alt="spinner"> </div>

We’re using .preloader as a wrapper, mostly because it helps us position the image on the page, but also because it will help us hide and reveal the page content while the loader works.

Let’s style it up:

.preloader { align-items: center; background: rgb(23, 22, 22); display: flex; height: 100vh; justify-content: center; left: 0; position: fixed; top: 0; transition: opacity 0.3s linear; width: 100%; z-index: 9999; }

This is doing a few things that are more than cosmetic:

  • We’re displaying the loader directly in the center of the screen, using flexbox properties and values.
  • We’ve made the element take up the entire width and height of the screen and given it a black (well, actually a really, really dark gray) background. That means anything behind it (like the page content) is completely hidden. If our page was a different background color (e.g. white), then we would adjust the loader’s background color accordingly.
  • The position is fixed so scrolling won’t affect it’s location on the page. Plus, the z-index is high enough that not other element should stack on top of it and block it from view.

This is what we should see so far when opening it up in the browser:

Some light JavaScript handles the hiding

We’ve got a fancy spinner that covers the entire page, whether we’re viewing this on small or large screens. No we can write some logic to make it fade out after a certain amount of time. That’ll take a small dose of JavaScript.

First, let’s select the .preloader element we just styled up:

const preloader = document.querySelector('.preloader');

It would actually be a lot easier to add a class to the loader that sets its opacity to zero. However, it wouldn’t be as smooth as what we’re doing here, which is using a tiny helping of JavaScript to create a fadeOut function.

const fadeEffect = setInterval(() => { // if we don't set opacity 1 in CSS, then // it will be equaled to "" -- that's why // we check it, and if so, set opacity to 1 if (!preloader.style.opacity) { preloader.style.opacity = 1; } if (preloader.style.opacity > 0) { preloader.style.opacity -= 0.1; } else { clearInterval(fadeEffect); } }, 100);

&#x1f4a1; jQuery has a function that does this right out of the box. Leverage that if you’re already using jQuery in your project. Otherwise, rolling it with vanilla JavaScript is the way to go.

Let me explain the JavaScript a little bit. As the comment says, if our .preloader element doesn’t have the opacity property set, then it will be equal to empty ("") and we can set it to a value of 1 manually to make sure it displays when the document loads.

Once we know the opacity is set, then we set manipulate it. The whole function is wrapped in setInterval and we check if the opacity property every 100 milliseconds to see if it is greater than zero. As long as it is above zero, we decrease its value in 0.1 increment, which creates a smooth effect that fades the element out over time.

Once we hit zero opacity, we clearInterval to stop the script from running infinitely. Feel free to play around with timing and decreasing points to fit your needs.

The last thing that left to do is to call the function. We’ll call it when the window loads:

window.addEventListener('load', fadeEffect);

We are intentionally using the load event instead of DOMContentLoaded because the DOMContentLoaded event is fired when the document has been completely loaded and parsed. That means it doesn’t *wait for stylesheets, images, and subframes to finish loading* *before it executes*. The load event can be used to detect a fully-loaded page, and that is exactly what we are looking for. Otherwise, the function would start before our CSS and SVG are ready.

Drop some content into the HTML and try things out. Here’s the demo again:

See the Pen
Preloader with JavaScript FadeOut
by Maks Akymenko (@maximakymenko)
on CodePen.

Congratulations! You now know how to build a pretty nice loading effect using nothing but an image and a pinch of CSS and JavaScript. Enjoy!

The post Let’s Make a Fancy, but Uncomplicated Page Loader appeared first on CSS-Tricks.

WordPress Plugin Overload? Give Jetpack a Try!

Css Tricks - Tue, 10/15/2019 - 3:20am

The WordPress ecosystem has a plentiful supply of plugins that offer everything from AMP to Zapier integration and so, so, so many other things in between. It's a significant contributor to what makes WordPress great because plugins can account for the needs of nearly any website.

How many plugins are installed on your WordPress site? Five? Fifteen? Fifty? We've been up to 31 plugins here at CSS-Tricks and we rely on them for everything from content delivery to performance. Why rebuild the wheel if you don't have to right? It's simply too easy and convenient to reach for something someone else has already created (and for free).

Whether you have a handful or a truckload of plugins, you know that each one adds a little bit of complexity to your site, especially when it comes to maintenance and updates. It's not uncommon to see that little badge at the top of the WordPress admin bar displaying a number of available plugin updates that are ready to install. The problem is that it can happen a lot and staying on top of updates turns almost into a game of Whack-a-Mole that not only eats up time, but risks conflicts on your site that could break things. Plugins are great! But mashing up code from third-party authors is always a (often slight) possibility.

One way to cut down on the number of plugins: Jetpack. It's a single plugin that provides the features and functionality of dozens. the number of plugins on CSS-Tricks would likely be much higher if we weren't relying on it for blocking spam comments, security scans, search, social sharing, post subscriptions, and displaying related posts... just to name a few. Jetpack is literally capable of so much that's hard to contain in a single post. We've outlined our favorites, though. And we can't recommend it enough.

Try Jetpack on your WordPress site to see all the ways it can help you.

The post WordPress Plugin Overload? Give Jetpack a Try! appeared first on CSS-Tricks.

Weaving One Element Over and Under Another Element

Css Tricks - Mon, 10/14/2019 - 8:46am

In this post, we’re going to use CSS superpowers to create a visual effect where two elements overlap and weave together. The epiphany for this design came during a short burst of spiritual inquisitiveness where I ended up at The Bible Project’s website. They make really cool animations, and I mean, really cool animations.

My attention, however, deviated from spiritualism to web design as I kept spotting these in-and-out border illustrations.

Screenshot form The Bible Project website.

I wondered if a similar could be made from pure CSS… and hallelujah, it’s possible!

See the Pen
Over and under border design using CSS
by Preethi Sam (@rpsthecoder)
on CodePen.

The principal CSS standards we use in this technique are CSS Blend Modes and CSS Grid.

First, we start with an image and a rotated frame in front of that image.

<div class="design"> <img src="bird-photo.jpg"> <div class="rotated-border"></div> </div> .design { position: relative; height: 300px; width: 300px; } .design > * { position: absolute; height: 100%; width: 100%; } .rotated-border { box-sizing: border-box; border: 15px #eb311f solid; transform: rotate(45deg); box-shadow: 0 0 10px #eb311f, inset 0 0 20px #eb311f; }

The red frame is created using border. Its box-sizing is set to include the border size in the dimensions of the box so that the frame is centered around the picture after being rotated. Otherwise, the frame will be bigger than the image and get pulled towards the bottom-right corner.

Then we pick a pair of opposite corners of the image and overlay their quadrants with their corresponding portion in a copy of the same image as before. This hides the red frame in those corners.

We basically need to make a cut portion of the image that looks like below to go on top of the red frame.

The visible two quadrants will lay on top of the .rotated-border element.

So, how do we alter the image so that only two quadrants of the image are visible? CSS Blend Modes! The multiply value is what we’re going to reach for in this instance. This adds transparency to an element by stripping white from the image to reveal what’s behind the element.

Chris has a nice demo showing how a red background shows through an image with the multiply blend mode.

See the Pen
Background Blending
by Chris Coyier (@chriscoyier)
on CodePen.

OK, nice, but what about those quadrants? We cover the quadrants we want to hide with white grid cells that will cause the image to bleed all the way through in those specific areas with a copy of the bird image right on top of it in the sourcecode.

<div id="design"> <img src="bird-photo.jpg"> <div class="rotated-border"></div> <div class="blend"> <!-- Copy of the same image --> <img src="bird-photo.jpg"> <div class="grid"> <!-- Quadrant 1: Top Left --> <div></div> <!-- Quadrant 2: Top Right --> <div data-white></div> <!-- Quadrant 3: Bottom Left --> <div data-white></div> <!-- Quadrant 4: Bottom Right --> <div></div> </div> </div> </div> .blend > * { position: absolute; height: 100%; width: 100%; } /* Establishes our grid */ .grid { display: grid; grid: repeat(2, 1fr) / repeat(2, 1fr); } /* Adds white to quadrants with this attribute */ [data-white]{ background-color: white; }

The result is a two-by-two grid with its top-right and bottom-left quadrants that are filled with white, while being grouped together with the image inside .blend.

To those of you new to CSS Grid, what we’re doing is adding a new .grid element that becomes a "grid" element when we declare display: grid;. Then we use the grid property (which is a shorthand that combines grid-template-columns and grid-template-rows) to create two equally spaced rows and columns. We’re basically saying, "Hey, grid, repeat two equal columns and repeat two equal rows inside of yourself to form four boxes."

A copy of the image and a grid with white cells on top of the red border.

Now we apply the multiply blend mode to .blend using the mix-blend-mode property.

.blend { mix-blend-mode: multiply; }

The result:

As you can see, the blend mode affects all four quadrants rather than just the two we want to see through. That means we can see through all four quadrants, which reveals all of the red rotated box.

We want to bring back the white we lost in top-left and bottom-right quadrants so that they hide the red rotated box behind them. Let’s add a second grid, this time on top of .blend in the sourcecode.

<div id="design"> <img src="bird-photo.jpg"> <div class="rotated-border"></div> <!-- A second grid --> <!-- This time, we're adding white to the image quandrants where we want to hide the red frame --> <div class="grid"> <!-- Quadrant 1: Top Left --> <div data-white></div> <!-- Quadrant 2: Top Right --> <div></div> <!-- Quadrant 3: Bottom Left --> <div></div> <!-- Quadrant 4: Bottom Right --> <div data-white></div> </div> <div class="blend"> <img src="bird-photo.jpg"> <div class="grid"> <!-- Quadrant 1: Top Left --> <div></div> <!-- Quadrant 2: Top Right --> <div data-white></div> <!-- Quadrant 3: Bottom Left --> <div data-white></div> <!-- Quadrant 4: Bottom Right --> <div></div> </div> </div> </div>

The result!

Summing up, the browser renders the elements in our demo like this:
??

  1. ??At bottommost is the bird image (represented by the leftmost grey shape in the diagram below)
  2. ??Then a rotated red frame
  3. ??On top of them is a grid with top-left and bottom-right white cells (corners where we don’t want to see the red frame in the final result)
  4. ??Followed by a copy of the bird image from before and a grid with top-right and bottom-left white cells (corners where we do want to see the red frame) – both grouped together and given the blending mode, multiply?.

You may have some questions about the approach I used in this post. Let me try to tackle those.

What about using CSS Masking instead of CSS Blend Modes?

For those of you familiar with CSS Masking – using either mask-image or clip-path – it can be an alternative to using blend mode.

I prefer blending because it has better browser support than masks and clipping. For instance, WebKit browsers don't support SVG <mask> reference in the CSS mask-image property and they also provide partial support for clip-path values, especially Safari.

Another reason for choosing blend mode is the convenience of being able to use grid to create a simple white structure instead of needing to create images (whether they are SVG or otherwise).

Then again, I’m fully on board the CSS blend mode train, having used it for knockout text, text fragmentation effect... and now this. I’m pretty much all in on it.

Why did you use grid for the quadrants?

The white boxes needed in the demo can be created by other means, of course, but grid makes things easier for me. For example, we could've leaned on flexbox instead. Use what works for you.

Why use a data-attribute on the grid quadrant elements to make them white?

I used it while coding the demo without thinking much about it – I guess it was quicker to type. I later thought of changing it to a class, but left it as it is because the HTML looked neater that way… at least to me. :)

Is multiply the only blend mode that works for this example?

Nope. If you already know about blend modes then you probably also know you can use either screen, darken, or lighten to get a similar effect. (Both screen and lighten will need black grid cells instead of white.)

The post Weaving One Element Over and Under Another Element appeared first on CSS-Tricks.

Stop Animations During Window Resizing

Css Tricks - Mon, 10/14/2019 - 3:57am

Say you have page that has a bunch of transitions and animations on all sorts of elements. Some of them get triggered when the window is resized because they have to do with size of the page or position or padding or something. It doesn't really matter what it is, the fact that the transition or animation runs may contribute to a feeling of jankiness as you resize the window. If those transitions or animations don't deliver any benefit in those scenarios, you can turn them off!

The trick is to apply a class that universally shuts off all the transitions and animations:

let resizeTimer; window.addEventListener("resize", () => { document.body.classList.add("resize-animation-stopper"); clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { document.body.classList.remove("resize-animation-stopper"); }, 400); });

Now we have a resize-animation-stopper class on the <body> that can force disable any transition or animation while the window is being resized, and goes away after the timeout clears.

.resize-animation-stopper * { animation: none !important; transition: none !important; }

There is probably some more performant way of doing this than setTimeout, but that's the concept. I use this right here on this very site (v17) after noticing some significant resizing jank. It hasn't entirely eliminated the jank but it's noticeably better.

Here's an example:

See the Pen
Turn off animation on resize?
by Chris Coyier (@chriscoyier)
on CodePen.

That demo is mostly just for the working code. There probably isn't enough going on transitions-wise to notice much resize jank.

The post Stop Animations During Window Resizing appeared first on CSS-Tricks.

Two Images and an API: Everything We Need for Recoloring Products

Css Tricks - Fri, 10/11/2019 - 4:34am

I recently found a solution to dynamically update the color of any product image. So with just one <img> of a product, we can colorize it in different ways to show different color options. We don’t even need any fancy SVG or CSS to get it done!

We’ll be using an image editor (e.g. Photoshop or Sketch) and the image transformation service imgix. (This isn’t a sponsored post and there is no affiliation here — it’s just a technique I want to share.)

See the Pen
Dynamic Car color
by Der Dooley (@ddools)
on CodePen.

I work with a travel software company called CarTrawler on the engineering team, and I recently undertook a project a revamp our car images library that we use to display car rental search results. I wanted to take this opportunity to introduce dynamically colored cars.

We may sometimes load up to 200 different cars at the same time, so speed and performance are key requirements. We also have five different products throughout unique code bases, so avoiding over-engineering is vital to success.

I wanted to be able to dynamically change the color of each of these cars without needing additional front-end changes to the code.

Step 1: The Base Layer

I'm using car photos here, but this technique could be applied to any product. First we need a base layer. This is the default layer we would display without any color and it should look good on its own.

Step 2: The Paint Layer

Next we create a paint layer that is the same dimensions as the base layer, but only contains the areas where the colors should change dynamically.

A light color is key for the paint layer. Using white or a light shade of gray gives us a great advantage because we are ultimately “blending” this image with color. Anything darker or in a different hue would make it hard to mix this base color with other colors.

Step 3: Using the imgix API

This is where things get interesting. I'm going to leverage multiple parameters from the imgix API. Let's apply a black to our paint layer.

(Source URL)

We changed the color by applying a standard black hex value of #000000.

https://ddools.imgix.net/cars/paint.png?w=600&bri=-18&con=26&monochrome=000000

If you noticed the URL of the image above, you might be wondering: What the heck are all those parameters? The imgix API docs have a lot of great information, so no need to go into greater detail here. But I will explain the parameters I used.

  • w. The width I want the image to be
  • bri. Adjusts the brightness level
  • con. Adjusts the amount of contrast
  • monochrome. The dynamic hex color

Because we are going to stack our layers via imgix we will need to encode our paint layer. That means replacing some of the characters in the URL with encoded values — like we’d do if we were using inline SVG as a background image in CSS.

https%3A%2F%2Fddools.imgix.net%2Fcars%2Fpaint.png%3Fw%3D600%26bri%3D-18%26con%3D26%26monochrome%3D000000 Step 4: Stack the Layers

Now we are going to use imgix’s watermark parameter to stack the paint layer on top of our base layer.

https://ddools.imgix.net/cars/base.png?w=600&mark-align=center,middle&mark=[PAINTLAYER]

Let's look at the parameters being used:

  • w. This is the image width and it must be identical for both layers.
  • mark-align. This centers the paint layer on top of the base layer.
  • mark. This is where the encoded paint layer goes.

In the end, you will get a single URL that will look like something like this:

https://ddools.imgix.net/cars/base.png?w=600&mark-align=center,middle&mark=https%3A%2F%2Fddools.imgix.net%2Fcars%2Fpaint.png%3Fw%3D600%26bri%3D-18%26con%3D26%26monochrome%3D000000

That gives the car in black:

(Source URL)

Now that we have one URL, we can basically swap out the black hex value with any other colors we want. Let’s try blue!

(Source URL)

Or green!

(Source URL)

Why not red?

(Source URL)

That's it! There are certainly other ways to accomplish the same thing, but this seems so straightforward that it’s worth sharing. There was no need code a bunch of additional functionality. No complex libraries to manage or wrangle. All we need is a couple of images that an online tool will stack and blend for us. Seems like a pretty reasonable solution!

The post Two Images and an API: Everything We Need for Recoloring Products appeared first on CSS-Tricks.

The Teletype Text Element Lives On… at Least on This Site

Css Tricks - Fri, 10/11/2019 - 4:33am

It was this: <tt>

I say "was" because it's deprecated. It may still "work" (like everybody's favorite <marquee> in some browsers), but it could stop working anytime, they say. The whole purpose of it was to display text in a monospace font, like the way Teletype machines used to.

Dave used it jokingly the other day.

Per recent events: As you can see by this official transcript, Dave Rupert LLC has done nothing wrong...

<tt>
Client: This is the greatest call I've ever been on.
Dave Rupert LLC: Definitely and we didn't even do anything illegal or quid pro quo'y.
</tt>

— Dave Rupert (@davatron5000) September 24, 2019

Which got me thinking how much I used to use that element!

&#x1f62c;&#x1f62c;&#x1f62c; pic.twitter.com/lDZpKx9Moy

— Chris Coyier (@chriscoyier) September 24, 2019

Right here on CSS-Tricks. See, in my early days, I learned about that element and how its job is to set text as monospace. I thought, oh! like code! and then for years that's how I marked up code on this site. I had never heard of the <code> element! When I did, I switched over to that. But I still haven't updated every single article from <tt> to <code>. It lingers in articles like this:

I bring this up just because it's a funny little example of not knowing what you don't know. It's worth having a little sympathy for people early in their journey and just doing things that get the job done because that's all they know. We've all been there... and are always still there to some degree.

The post The Teletype Text Element Lives On… at Least on This Site appeared first on CSS-Tricks.

Syndicate content
©2003 - Present Akamai Design & Development.