Web Standards

ImageKit.io: Image Optimization That Plugs Into Your Infrastructure

Css Tricks - Thu, 10/24/2019 - 4:20am

Images are the most efficient means to showcase a product or service on a website. They make up for most of the visual content on our website.

But, the more images a webpage has, the more bandwidth it consumes, affecting the page load speed - a raging factor having a significant impact on not just our search ranking, but also on our conversion rates.

Image optimization helps serve the right images and improve the page load time. A faster website has a positive impact on our user experience.

With image optimization becoming a standard practice for websites and apps, finding a service that offers the most competent features with a coherent pricing model, one that integrates seamlessly with the existing infrastructure and business needs, is paramount to any website and its efficiency.

So what are the most common criteria for selecting an image optimization tool?

The importance of image optimization isn’t up for debate, our choice of tool or service for it may just be. And it is a factor we should consider carefully. So where are the challenges?

  • Inability to integrate with existing infrastructure - Image optimization is very fundamental on modern websites. To implement it, we should not have to make any changes to our existing setup. But unfortunately, a lot of these tools or services can only be used with specific CDNs or are incapable of being integrated with our existing image servers or storage.
  • Dependency on their image storage - Some tools require us to move our images to their system, making us more dependent on them — an added hassle. And nobody wants to spend their time and effort on a virtually unnecessary step like migrating assets from one platform to another (and may be migrating to some other service in the future, if this one doesn’t work out). Not when it’s not needed. Not if we have hundreds of thousands of images and can never be sure if all the images have been migrated to the new tool or not.

Apart from the above challenges, it is possible that the choice of tool could be expensive or has a complex pricing structure. Or could have only the basic image-related features or not deliver excellent performance across the globe.

Enter ImageKit.io.

It is the only tool that we will need for image optimization and transformation with minimal effort and almost no changes to our existing infrastructure.

It is a complete image CDN with optimization and transformation capabilities for images on websites and apps. What does that mean?

Feed ImageKit.io an original, un-optimized image and fetch it using an ImageKit.io URL, and it shall deliver an optimized, rightly resized image to our user’s devices!

For example:

ImageKit.io resizes the image automatically by simply specifying the size in the image URL.


Here, the width and height of the final image are specified with “w” and “h” parameters in the URL. The output image has dimensions 300×100px, scaled down from an original size of 1000×1000px.

As we know, the right image formats can have a significant impact on our website’s bandwidth consumption.

For instance, the following PNG image,


is almost 2.5x the size of its JPG variant.

ImageKit.io automatically uses the correct output image format based on image content, image quality, browser support, and user device capabilities. Also, the above image will be converted and delivered as a WebP for all browsers supporting the WebP image format.

Just turn it on, and we’re good to go!

And not just simple resizing and cropping, ImageKit.io allows for more advanced transformations like smart crop, image and text overlays, image trimming, blurring, contrast and sharpness correction, and many more. It also comes with advanced delivery features like Brotli compression for SVG images and image security. ImageKit.io is the solution to all our image optimization needs. And more.

It also comes bundled with a stellar infrastructure — AWS CloudFront CDN, multi-region core processing servers, and a media library with automatic global backups.


It isn’t enough to find the most appropriate tool for our website. It should also provide an optimum experience fitting in just right with our existing setup.

ImageKit.io integration with the existing infrastructure With S3 bucket or other web servers

It is usually a tedious task to integrate any image optimization tool into our infrastructure. For example, for images, we would already have a CMS in place to upload the images. And a server or storage to store all of those images. We would not want to make any significant changes to the existing setup that could potentially disrupt all our team's processes.

But with ImageKit.io, the whole process from integration to image delivery takes just a few minutes. ImageKit.io allows us to plug our S3 bucket or webserver and start delivering optimized and transformed images instantly. No movement or re-upload of images is required. It takes just a few minutes to get the best optimization results.

We can attach our server or storage using “ADD ORIGIN” in the ImageKit.io dashboard

Such simple integrations with AWS S3 or web servers are not available even with some leading players in the market.

Images fetched through ImageKit.io are automatically optimized and converted to the appropriate format. And we can resize and transform any image by just adding URL parameters.

For example:

Image with width 300px and height is adjusted automatically to preserve aspect ratio:




We are using https://ik.imagekit.io/your_imagekit_id format for the URLs, but custom domain names are available with ImageKIt.io.

Learn more about it here.

Media library

ImageKit.io also provides a media library, a feature missing in many prominent image optimization tools. Media library is a highly available file storage for all ImageKit.io users. It comes with a simple user interface to upload, search, and manage files, images, and folders.

ImageKit.io Media Library With platforms like Magento and WordPress

Most SMBs use WordPress to build their websites. ImageKit.io proves handy and almost effortless to set up for these websites.

Installing a plugin on WordPress and making some minor changes in the settings from the WP plugin is all we need to do to integrate ImageKit.io with our WordPress website for all essential optimizations. Learn more about it here.

Similarly, we can integrate ImageKit.io with our Magento store. The essential format and quality optimizations do not require any code change and can be set up by making some changes in Settings in the Magento Admin Panel. Learn more about it here.

For advanced use cases like granular image quality control, smart cropping, watermarking, text overlays, and DPR support, ImageKit.io offers a much better solution, with more robust features, more control over the optimizations and more complex transformations, than the ones provided natively by WordPress or Magento. And we can implement them by making some changes in our website's template files.

With other CDNs

Most businesses use CDNs for their websites, usually under contracts, or running processes other than or in addition to image optimizations on these CDNs, or simply because a particular CDN performs better in a specific region.

Even then, it is possible to use ImageKit.io with our choice of CDN. They support integrations with:

  • Akamai
  • Azure
  • Alibaba Cloud CDN
  • CloudFlare (if one is on an Enterprise plan in CloudFlare)
  • CloudFront
  • Fastly
  • Google CDN
  • Zenedge

To ensure correct optimizations and caching on our CDN, their team works closely with their customer’s team to set up the configuration.

Custom domain names

As image optimization has become a norm, services like LetsEncrypt, which make obtaining and deploying an SSL certificate free, have also become standard practice. In such a scenario, enabling a custom domain name should not be charged heavily.

ImageKit.io helps us out here too.

It offers one custom domain name like images.example.com, SSL and HTTP2 enabled, free of charge, with each paid account. Additional domain names are available at a nominal one-time fee of $50. There are no hidden costs after that.

One ImageKit.io account, multiple websites

For image optimization needs for multiple websites or agencies handling hundreds of websites, ImageKit.io would prove to be an ideal solution. We’re free to attach as many “origins” (storages or servers) with ImageKit.io. What that means is each website has its storage or image server, which can be mapped to separate URLs within the same ImageKit.io account.

Configure the origin for a new site in the ImageKit.io dashboard and map it against a URL endpoint

The added advantage of using ImageKit.io for multiple websites and apps is their pricing model. When one consolidates the usage across their many business accounts, and if it crosses the 1TB mark, they can reach out to ImageKit.io’s team for a special quote. Learn more about it here.

Multiple server regions

ImageKit.io is a global image CDN, It has a distributed infrastructure and processing regions around the world, in North Virginia (US East), North California (US West), Frankfurt (EU), Mumbai (India), Sydney (Australia) and Singapore, aiming to reduce latency between their servers and our image origins.

Multiple server regions with processing and delivery nodes across the globe

Additionally, ImageKit.io stores the images (transformed as well as original) in their cache after fetching them from our origins. This intermediate caching is done to avoid processing the images again. Doing so not only reduces the load on our origin servers and storage but also reduces data transfer costs from them.

Custom cache time

There are times when a shorter cache time is required. For cases where one or more images are set to change at intervals, while the others remain the same, ImageKit.io offers the option to set up custom cache times in place of the default 180 days preset in ImageKit.io, giving us more control over how our resources are cached.

Custom cache time

This feature is usually not provided by third-party image CDNs or is available to enterprise customers only, but it is available with ImageKit.io on request.

Deliver non-image files through ImageKit.io CDN

ImageKit.io comes integrated with a CDN to store and serve resources. And while the primary use case is to deliver optimized images, it can do the same for the other static assets on our website, like JS, CSS as well as fonts.

There is no point dividing our static resources between two services when one, ImageKit.io, can do the whole job on its own.

It’s worth a mention here that though ImageKit.io provides delivery for non-image assets, it does not process or optimize them.

With ImageKit.io’s pricing model in mind, using their CDN may prove beneficial as it bills only based on one parameter — the total bandwidth consumed.

Cost efficiency

Most image optimization tools charge us for image storage or bill us based on requests or the number of master images or transformations.

ImageKit.io bills its customers on a single parameter, their output bandwidth. With ImageKit.io, we can optimize and transform to our heart’s content, without worrying about the costs they may incur. With our focus no longer on the billing costs, we can now focus on important tasks, like optimizing our images and website.

Usually, when an ImageKit.io account crosses 1TB total bandwidth consumption, that account becomes eligible for special pricing.

One can contact their team for a quote after crossing that threshold.

Final thoughts

Image optimization holds many benefits, but are we doing it right? And are we using the best service in the market for it?

ImageKit.io might prove to be the solution for all image optimization and management needs. But we don’t have to take their word for it. We can know for ourselves by joining the many developers and companies using ImageKit.io to deliver best-in-class image optimizations to their users by signing up for free here.

The post ImageKit.io: Image Optimization That Plugs Into Your Infrastructure appeared first on CSS-Tricks.

Why Are Accessible Websites so Hard to Build?

Css Tricks - Wed, 10/23/2019 - 7:36am

I was chatting with some front-end folks the other day about why so many companies struggle at making accessible websites. Why are accessible websites so hard to build? We learn about HTML, we make sure things are semantic and — voila! @— we have an accessible website. During the course of conversation, someone mentioned the Domino's pizza legal case, which is perhaps the most public example of a company being sued because of a lack of accessibility.

Here’s an interesting tidbit from that link:

According to CNBC, the number of lawsuits over inaccessible websites jumped 58 percent last year over 2017, to more than 2,200.

Inaccessible websites are not just a consideration for designers and engineers but a serious problem for a company’s legal team as well. Thankfully, it seems more of these cases will be brought to trial and (my personal hope is) this will get folks to care more about semantics and front-end development best practices. Although I'd like to think that companies would do what’s best for the web and make websites that meet the baseline requirements without a legal threat, we absolutely need to make inaccessible websites illegal for folks to really pay attention to this issue.

However! I also worry about attributing what might simply be a lack of knowledge to malice. I reckon a lot of websites have bad accessibility not because folks don’t care, but because they don’t know there's an issue in the first place. As my conversation with front-end engineers progressed, I realized that the reason accessibility isn’t tackled seriously probably doesn’t have anything to do with bandwidth, or experience, or money.

I reckon the problem is that the accessibility of a website can be invisibly and silently broken.

Here’s an example: when developing a site, JavaScript errors are probably going to be caught because everything breaks if something goes wrong. And CSS bugs are going to get caught because something will look off. But the accessibility or performance of a website can go from okay to terrible overnight and with no warning whatsoever. The only way to fix these invisibly broken things is to first make them visible.

So, here’s an idea: what if our text editors caught accessibility issues and showed them to us during development? It could look something like this:

I’m sure there are a ton of other ways we can make accessibility issues more public and visible. There are tools such as Lighthouse and browser extensions that are already out there, but making accessibility (and even performance, another silent fail) a part of our minute-to-minute workflow ensures that we can’t ignore it. Something like this would encourage us to learn about the problems, give us links to potential solutions, and encourage us all to care for a relatively misunderstood part of front-end development.

The post Why Are Accessible Websites so Hard to Build? appeared first on CSS-Tricks.

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.


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.


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


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.

8 Psychology-Based Design Hacks That Will Make You A Better UX Designer

Usability Geek - Tue, 10/22/2019 - 1:51am
If the first thought that crossed your mind when you read the title of the article was “What does Psychology has to do with UX Design?“  then, yes, that’s what we thought too, now that we’re on the...
Categories: Web Standards

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


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 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.

Book draft: overflow chapter

QuirksBlog - Thu, 10/17/2019 - 4:34am

I am going to write a “CSS for JavaScripters” book, and therefore I need to figure out how to explain CSS to JavaScripters. This series of article snippets are a sort of try-out — pre-drafts I’d like to get feedback on in order to figure out if I’m on the right track.

Today I present the first draft of the short overflow article. Feedback would be greatly appreciated.


body > img { max-width: 100%; border: 1px solid; }

"Web design is a constant battle against overflow."

- Rachel Andrew

Not knowing how tall something is is fundamental to web design. For instance, you cannot know in advance how long the texts will be that will be shown in your site. What happens if if the final text is much longer than the fake text you used during production? Or what if there's a wide image you hadn't counted on?

In both cases the content of your blocks will become larger than you expected, and if you've given them a fixed width or height that might lead to overflow: content escaping from the block — or at least, attempting to escape.

The easiest way to avoid overflow is not giving your blocks a fixed height in the first place. If you allow them to grow as tall and wide as they need to be you avoid quite a few problems.

This short chapter discusses how to deal with overflow.

CSS Is Awesome

The most famous example of overflow is the "CSS is Awesome" meme that's been around ever since 2009.

Born out of one web developer's frustration with CSS's overflow behavior, this meme took on a life of its own and became an example of what was wrong with CSS. Why would the 'Awesome' flow out of the box? Why should CSS be so complicated? Couldn't the box simply grow to contain the 'Awesome'?

Sure it could! And it would, except that you specifically instructed the box not to by giving it a fixed width. You could have used min-width or flexbox — both are good in dealing with unexpectedly large content — but you didn't. No doubt you had good reasons, but since it was your decision, the onus of solving any resulting issues is on you.

In these cases, the overflow declaration is your friend. The overflow declaration

The overflow declaration allows you to define what to do with content that overflows its box. It has four values, visible, hidden, scroll, and auto. The default value is visible, and that's the one that causes the 'CSS is Awesome' effect.

overflow: visible means that you allow the content to spill out of its block. Although that keeps the content readable, it also means the content might overlap with the block below or to the right of the affected block, which can be very ugly.

When calculating the position of other blocks, the browsers' layout algorithm uses the width and height of the box you defined, and disregards the fact that content may be spilling out of the block. In fact, at that point in the algorithm the browsers have no way of knowing that the content overflows. [FACT-CHECK THIS]

Thus, when calculating the position of the next block the browsers place the block exactly where it should be given the height of the previous block and the margins of both. They do not pay the overflow any mind, wbich may cause the overflowing content to overlap the content of the next block.

Sometimes this is what you want — or rather, what you’re forced to live with. More often, though, you want to either generate scrollbars or hide the overflowing content entirely.

overflow: hidden hides the overflowing content. This creates a pleasing visual effect, but now there's no way for the user to get to the content. Therefore, hidden is something of a nuclear option: necessary in a few cases, but to be avoided whenever there's a better way of handling the situation.

overflow: scroll and overflow: auto generate scrollbars. The auto value generates scrollbars when they're necessary, while scroll scroll value always does so, even when no scrollbars are needed.

If scroll always generates those ungainly scrollbars, even when they're not needed, and auto only generates them when necessary, why would you ever use scroll? The reason is that a content change that generates or removes a scrollbar can be quite ugly.

Suppose you have a block with overflow: auto that initially does not need scrollbars. Then a script adds a lot of content to the block, causing overflow, and thus the generation of a scrollbar. Not only is this quite ugly in itself, but on some systems [BE MORE SPECIFIC] the scrollbar itself takes up about 16px of width and thus narrows the content area, which may lead to the reflowing of the text and even more overflow. And when the content is removed, all of that happens in reverse.

All this can give a quite jarring effect. For instance, see the position of the word "serves" in the two screenshots below. The creation of a scrollbar forces it to the next line, and that might be something you want to avoid.

The easiest way of preventing that effect is by giving the block overflow: scroll from the outset. Sure, the scrollbars may not be needed, but if they are there's no moving around of the content.

Block Formatting Context

[This is a practical tip that readers need to know about.]

An overflow value of anything but visible will create a new block formatting context. In old-fashioned float-based layouts it is sometimes necessary to create a block formatting context in order to contain a bunch of floats. (Just nod wisely for the moment; we'll get back to this.)

The easiest way of doing this is to add overflow: auto to the block, even though the block has no set height and the content will never actually overflow.

So if you're working in an old codebase and encounter a bunch of unexplained overflow: auto (or hidden) declarations on blocks that have height: auto, remember that they're meant to keep a float-based layout working properly. Only remove those overflows once you switched from floats to a modern layout system like grid or flex. If you do not intend to switch, leave the overflows in place as well.

Related declarations

In addition to the overflow declaration, there are also overflow-x and overflow-y declarations. They do what you'd expect them to do: they set the overflow on only the horizontal x-axis, or only the vertical y-axis. Otherwise they work exactly like overflow.

Also, iOS supports overflow-scrolling: touch, which enables momentum-based scrolling for overflowing elements. Without this declaration (or, more precisely, with the default overflow-scrolling: auto in place), overflowing elements scroll normally, i.e. they stop scrolling as soon as your finger leaves the screen. Android devices always use momentum-based scrolling, so they do not need this declaration. It doesn't hurt them, either, so it's perfectly safe to use. [TEST]


The ending is a bit abrupt, but I'm not entirely sure what to say next. Also, I'm not yet sure which chapter will come next, so I can't write a segue.

Anyway, please let me know what you think. I'm especially looking for feedback from JavaScript developers who are not all that good at CSS.

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
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.

Syndicate content
©2003 - Present Akamai Design & Development.