Front End Web Development

Getting Deep into Shadows

Css Tricks - Mon, 02/22/2021 - 6:00am

Let’s talk shadows in web design. Shadows add texture, perspective, and emphasize the dimensions of objects. In web design, using light and shadow can add physical realism and can be used to make rich, tactile interfaces.

Take the landing page below. It is for cycling tours in Iceland. Notice the embellished drop shadow of the cyclist and how it creates the perception that they are flying above not only the content on the page, but the page itself, as though they are “popping” over the screen. It feels dynamic and immediate, which is perfect for the theme of adventure.

Credit: Kate Hahu

Compare that with this next example. It’s a “flat” design, sans shadows. In this case, the bike itself is the focal point. The absence of depth and realism allows the bike to stand out on its own.

Credit: saravana

You can appreciate the differences between these approaches. Using shadows and depth is a design choice; they should support the theme and the message you want the content to convey.

Light and shadows

As we just saw, depth can enhance content. And what exactly makes a shadow? Light!

It’s impossible to talk about shadow without getting into light. It controls the direction of a shadow as well as how deep or shallow the shadow appears. You can’t have one without the other.

Google’s Material Design design system is a good example of employing light and shadows effectively. You’ve certainly encountered Material Design’s aesthetics because Google employs it on nearly all of its products.

The design system takes cues from the physical world and expresses interfaces in three-dimensional space using light, surfaces, and cast shadows. Their guidelines on using light and shadows covers this in great detail.

In the Material Design environment, virtual lights illuminate the UI. Key lights create sharper, directional shadows, called key shadows. Ambient light appears from all angles to create diffused, soft shadows, called ambient shadows.

Shadows are a core component of Material Design. Compare that with Apple’s Human Interface Guidelines for macOS, where translucency and blurring is more of a driving factor for evoking depth.

In this case, light is still an influential factor, as it allows elements to either blend into the desktop, or even into other panels in the UI. Again, it’s is a design choice to employ this in your interface. Either way, you can see how light influences the visual perception of depth.

Light sources and color

Now that we understand the relationship between light and shadows, we ought to dig in a little deeper to see how light affects shadows. We’ve already seen how the strength of light produces shadows at different depths. But there’s a lot to say about the way light affects the direction and color of shadows.

There are two kinds of shadows that occur when a light shines on an object, a drop shadow and a form shadow.

Drop shadows

A drop shadow is cast when an object blocks a light source. A drop shadow can vary in tone and value. Color terminology can be dense and confusing, so let’s talk about tone and value for a moment.

Tone is a hue blended with grey. Value describes the overall lightness or darkness of a color. Value is a big deal in painting as it is how the artist translates light and object relationships to color.

In the web design world, these facets of color are intrinsic to the color picker UI.

Form shadows

A form shadow, on the other hand, is the side of an object facing away from the light source. A form shadow has softer, less defined edges than a drop shadow. Form shadows illustrate the volume and depth of an object.

The appearance of a shadow depends on the direction of light, the intensity of light, and the distance between the object and the surface where the shadow is cast. The stronger the light, the darker and sharper the shadow is. The softer the light, the fainter and softer the shadow is. In some cases, we get two distinct shadows for directional light. The umbra is where light is obstructed and penumbra is where light is cast off.

If a surface is close to an object, the shadow will be sharper. If a surface is further away, the shadow will be fainter. This is not some abstract scientific stuff. This is stuff we encounter every day, whether you realize it or not.

Light may also be reflected from sides of an object or another surface. Bright surfaces reflect light, dark surfaces absorb light.

These are the most valuable facets of light to understand for web design. The physics behind light is a complex topic, I have just lightly touched on some of it here. If you’d like to see explicit examples of what shadows are cast based on different light sources, this guide to drawing shadows for comics is instructive.

Positioning light sources

Remember, shadows go hand-in-hand with light, so defining a light source — even though there technically isn’t one — is the way to create impressive shadow effects. The trick is to consistently add shadows relative to the light source. A light source positioned above an element will cast a shadow below the element. Placing a light source to the left of an element will cast a shadow to the right. Placing multiple light sources to the top, bottom, left and right of an element actually casts no shadow at all!

A light source can be projected in any direction you choose. Just make sure it’s used consistently in your design, so the shadow on one element matches other shadows on the page.

Elevation

Shadows can also convey elevation. Once again, Material Design is a good example because it demonstrates how shadows are used to create perceived separation between elements.

Credit: Nate Wilson Inner shadows

Speaking of elevation, the box-shadow property is the only property that can create inner shadows for a sunken effect. So, instead of elevating up, the element appears to be pressed in. That’s thanks to the inset keyword.

That good for something like an effect where clicking a button appears to physically press it.

CodePen Embed Fallback

It’s also possible to “fake” an inner text shadow with a little trickery that’s mostly supported across browsers:

CodePen Embed Fallback Layering shadows

We’re not limited to a single shadow per element! For example, we can provide a comma-separated list of shadows on the box-shadow property. Why would we want to do that? Smoother shadows, for one.

CodePen Embed Fallback

Interesting effects is another.

CodePen Embed Fallback

Layering shadows can even enhance typography using the text-shadow property.

CodePen Embed Fallback

Just know that layering shadows is a little different for filter: drop-shadow() It’s syntax also takes a list, but it’s space-separated instead of comma-separated.

.box { box-shadow: 0 2px 2px #555, /* commas */ 0 6px 5px #777, 0 12px 10px #999 ; } .box { filter: drop-shadow(0 2px 2px #555) /* spaces */ drop-shadow(0 6px 5px #777) drop-shadow(0 12px 10px #999); }

Another thing? Shadows stack on top of one another, in the order they are declared where the top shadow is the first one in the list.

You may have guessed that drop-shadow() works a little differently here. Shadows are added exponentially, i.e. 2^number of shadows - 1.

Here’s how that works:

  • 1 shadow = (2^1 – 1). One shadow is rendered.
  • 2 shadows = (2^2 – 1). Three shadows are rendered.
  • 3 shadows = (2^3 – 1). Seven shadows are rendered.

Or, in code:

.one-shadow { filter: drop-shadow(20px 20px 0 grey); } .three-shadows { filter: drop-shadow(20px 20px 0 grey) drop-shadow(40px 0 0 yellow); } .seven-shadows { filter: drop-shadow(20px 20px 0 grey) drop-shadow(40px 0 0 yellow); drop-shadow(80px 0 0 red); }

The <feDropShadow> element works the exact same way for SVGs.

Shadows and accessibility

Here’s something for you to chew on: shadows can help improve accessibility.

Google conducted a study with low-vision participants to better understand how shadows and outlines impact an individual’s ability to identify and interact with a component. They found that using shadows and outlines:

  • increases the ease and speed of finding a component when scanning pages, and
  • improves one’s ability to determine whether or not a component is interactive.

That wasn’t a wide-ranging scientific study or anything, so let’s turn around and see what the W3C says in it’s guidelines for WCAG 2.0 standards:

[…] the designer might darken the background behind the letter, or add a thin black outline (at least one pixel wide) around the letter in order to keep the contrast ratio between the letter and the background above 4.5:1.

That’s talking about light text on a light background. WCAG recommends a contrast ratio that’s at least 4.5:1 between text and images. You can use text shadows to add a stronger contrast between them.

Photo credit: Woody Van der Straeten Shadows and performance

Before diving into shadows and adding them on all the things, it’s worth calling out that they do affect performance.

For example, filter: drop-shadow is hardware-accelerated by some browsers. A new compositor layer may be created for that element, and offloaded to the GPU. You don’t want to have too many layers, as it takes up limited GPU memory, and will eventually degrade performance. You can assess this in your browser’s DevTools.

Blurring is an expensive operation, so use it sparingly. When you blur something, it mixes the colors from pixels all around the output pixel to generate a blurred result. For example, if your <blur-radius> parameter is 2px, then the filter needs to look at two pixels in every direction around each output pixel to generate the mixed color. This happens for each output pixel, so that means a lot of calculations that grow exponentially. So, shadows with a large blur radius are generally slower to render than other shadows.

Did you know?

Did you know that shadows don’t influence the document layout?

A shadow is the same size as the element it targets. You can modify the size of a box-shadow (through the spread radius parameter), but other properties cannot modify the shadow size.

And did you know that a shadow implicitly has a lower z-index than elements? That’s why shadows sit below other elements.

And what about clipping and masking? If an element with a box-shadow is clipped (with clip-path) or uses a mask (with mask), the shadow isn’t shown. Conversely, if an element with text-shadow or filter: drop-shadow() is clipped, a shadow is shown, as long as it is within the clip region.

Here’s another: We can’t create oblique shadows (with diagonal lines) with shadow properties. That requires creating a shadow element and use a transform:skew() on it.

CodePen Embed Fallback

Oh, and one more: box-shadow follows border-radius. If an element has rounded corners, the shadow is rounded as well. In other words, the shadow mirrors the shape of the box. On the other hand, filter: drop-shadow() can create an irregular shape because it respects transparency and follows the shape of the content.

Best use cases for different types of shadows

Practically anything on the web can have a shadow and there are multiple CSS properties and functions that create shadows. But choosing the right type of shadow is what makes a shadow effective.

Let’s evaluate the options:

  • box-shadow: This CSS property creates shadows that conform to the elements bounding box. It’s versatile and can be used on anything from cards to buttons to just about anything where the shadow simply needs to follow the element’s box.
  • text-shadow: This is a CSS property that creates shadows specifically for text elements.
  • filter: drop-shadow(): The CSS property here is filter, but what create the shadow is the drop-shadow function it accepts. What makes this type of shadow different from, say box-shadow, is that it follows the rendered shape of any element (including pseudos).
  • <feDropShadow>: This is actually an SVG element, whereas the rest are CSS properties. So, you would use this to create drop shadows directly in SVG markup.

Once you get the hang of the different types of shadows and each one’s unique shadow-creating powers, the possibilities for shadow effects feels endless. From simple drop shadows to floating elements, and even inner shadows, we can create interesting visuals that add extra meaning or value to UI.

CodePen Embed Fallback

The same goes for text shadows.

CodePen Embed Fallback Shadows in the wild

Shadows are ubiquitous. We’re seeing them used in new and interesting ways all the time.

Have you heard the buzzword “neumorphism” floating around lately? That’s all about shadows. Here’s an implementation by Maria Muñoz:

CodePen Embed Fallback

Yuan Chuan, who makes amazing generative art, calls shadows a secret weapon in UI design:

CSS relies on existing DOM structure in the browser. It’s not possible to generate new elements other than ::before and ::after. Sometimes I really wish CSS had the ability to do so straightforwardly.

Yet, we can partially make up for this by creating various shadows and gradients entirely in CSS.

That’s why having drop-shadow is so exciting. Together with text-shadow and box-shadow we can do a lot more.

Just check out how he uses drop shadows to create intricate patterns.

CodePen Embed Fallback

Yes, that’s pretty crazy. And speaking of crazy, it’s worth mentioning that going too crazy can result in poor performance, so tread carefully.

What about pseudo-elements?

Oh yes, shadow properties are supported by the ::before and ::after pseudo-elements.

Other pseudos that respect shadows? The ::first-letter pseudo-element accepts box-shadow and text-shadow. The ::first-line pseudo-element accepts text-shadow.

Look at how Jhey Tompkins got all creative using box-shadow on pseudo elements to create animated loaders.

CodePen Embed Fallback Animating shadows

Yes, we can make them move! The properties and function we’ve covered here are totally compatible with CSS animations and transitions. That means we can move shadows, blur shadows, expand/shrink shadows (with box-shadow), and alter the color.

Animating a shadow can provide a user with a cue that an element is interactive, or that an action has taken place. We saw earlier with our button example that an inset shadow showed that the button had been pressed. Another common animation pattern is elevating a card on hover.

CodePen Embed Fallback

If you want to optimize the animation performance, avoid animating box-shadow! It is more performant to animate drop-shadow(). But if you want the smoothest animation, a hack is the best option! Add an ::after pseudo-element with a bigger box-shadow, and animate its opacity instead.

CodePen Embed Fallback

Of course, there is a lot more you can animate. I will leave that exploration up to you!

Wrapping up

Phew, who knew there was so much to something as seemingly “simple” as CSS shadows! There’s the light source and how shadows are cast. The different types of shadows and their color. There’s using shadows for evoking depth, elevating elements and insetting them. There’s the fact that we can layer shadows on top of other shadows. And that we have a selection of CSS properties that we can use for different use cases. Then, there are the accessibility and performance implications that come with them. And, hey, animation is thing! That’s a heckuva lot!

Anyway, hopefully this broad overview gave you something new to chew on, or at the very least, helped you brush up on some concepts.

The post Getting Deep into Shadows appeared first on CSS-Tricks.

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

To the brain, reading computer code is not the same as reading language

Css Tricks - Mon, 02/22/2021 - 5:56am

One of the things I do when teaching beginning front-end development is ask students to describe what it’s like to read HTML. I give them pretty basic markup for a long-form article, and ask them to read it twice: first in the code, then on the front end.

The #1 common response I hear? It’s like learning a new language.

Of course it is, I tell them. It’s in the name: Hypertext Markup Language. So, I advise them to start treating the materials in the course like they’re learning French, Spanish, or any other language.

Then I wake up this morning and see this MIT study that reading computer code is not the same as reading language, even though they share similarities.

In spite of those similarities, MIT neuroscientists have found that reading computer code does not activate the regions of the brain that are involved in language processing. Instead, it activates a distributed network called the multiple demand network, which is also recruited for complex cognitive tasks such as solving math problems or crossword puzzles.

Duh, you might say. But wait, reading code actually appears to activate additional parts of the multiple demand network that make the task more or a near-match to mathematical reasoning than the exact same thing.

The MIT team found that reading computer code appears to activate both the left and right sides of the multiple demand network […]. This finding goes against the hypothesis that math and coding rely on the same brain mechanisms.

So, back to my HTML reading assignment. Is it better to teach code as a language for recognizing symbols that communicate to the browser what to do, or as a math skill that’s based on solving problems?

The answer is &#x1f937;‍♂️.

The most interesting thing about the study to me is not how to teach code, but rather how how I work with it. Chris always says a front-end developer is aware, and the fact that reading code taps on a region of the brain that’s responsible for handling multi-tasking and holding lots of information only supports that. It also explains why I personally get annoyed when I’m pulled away from my code or distracted from it—it’s like my brain has to drop all the plates it was balancing to pay attention to something else, then pick up and reassemble all the pieces before I can jump back in to what I was doing.

Direct Link to ArticlePermalink

The post To the brain, reading computer code is not the same as reading language appeared first on CSS-Tricks.

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

Clipping Scrollable Areas On The inline-start Side

Css Tricks - Fri, 02/19/2021 - 12:32pm

On a default left-to-right web page, “hanging” an element off the right side of the page (e.g. position: absolute; right: -100px;) triggers a horizontal scrollbar that scrolls as far as needed to make that whole element visible. But if you hang an element of the left side of the page, it’s just hidden (no scrollbar is triggered). That’s called “data loss” in CSS terms, if you’re fancy. The same is true for the top edge of the page (hidden) and bottom of the page (scrolling happens).

Ahmad puts a point on this. It’s just one of those CSS things that you just need to know. I love how Ahmad uses logical directions like inline-start direction (and block-start direction) to describe the issue because those directions change when the direction or writing mode of the page changes. If the page is right-to-left (RTL) like <html dir="rtl">, then horizontal edges where the data loss occurs are flipped (except in Firefox &#x1f937;‍♀️).

Direct Link to ArticlePermalink

The post Clipping Scrollable Areas On The inline-start Side appeared first on CSS-Tricks.

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

Three Ways to Blob with CSS and SVG

Css Tricks - Fri, 02/19/2021 - 6:09am

Blobs are the smooth, random, jelly-like shapes that have a whimsical quality and are just plain fun. They can be used as illustration elements and background effects on the web.

So, how are they made? Just crack open an illustration app and go for it, right? Sure, that’s cool. But we’re in a post here on CSS-Tricks, and it would be much more fun to look at the possibilities we have to do this with CSS and SVG — two of our favorite ingredients!

We actually have a few ways to go about blobs. Let’s check them out.

Drawing circles in SVG

Let’s start easy. We can draw SVG in something like Illustrator, Sketch, Figma or whatever, but we’re going to draw in SVG code instead.

SVG makes it pretty trivial to draw a circle, thanks to the appropriately named <circle> element:

<circle cx="100" cy="100" r="40" fill="red" />

Those funky attributes? They make sense once you break them down:

  • cx defines the x-coordinate of center of circle.
  • cy defines the y-coordinate.
  • r is the radius.
  • fill is used to fill the shape with color.

That snippet creates a circle with a 40px radius with its center at 100px on the x-axis and 100px on the y-axis. The coordinates start from the upper-left corner of the parent container.

Let’s create multiple overlapping circles like this:

<svg height="300" width="300"> <circle cx="80" cy="80" r="40" fill="red" /> <circle cx="120" cy="80" r="40" fill="red" /> <circle cx="150" cy="80" r="40" fill="red" /> <circle cx="150" cy="120" r="40" fill="red" /> <circle cx="100" cy="100" r="40" fill="red" /> </svg>

<svg> acts as the art board where all the different shapes and figures are drawn. So, its height and width indicates the size in which the whole drawing needs to be enclosed. If some part of figure is out of bounds of the SVG’s size, then that part will be truncated.

CodePen Embed Fallback

But blobs aren’t always so perfectly… round. We can mix things up by using <ellipse> instead of <circle>:

<ellipse cx="200" cy="80" rx="100" ry="50" fill="red" />

This is nearly identical to the circle except the change in tag name and two radii values to define the horizontal (rx) and vertical (ry) radii separately. The funny thing is that we can still get a perfect circle if we want if the radii values are the same. So, in a sense, <ellipse> is a little more versatile.

And, if all you need is a circle, we could probably lean on CSS without SVG at all. Any box element can become a circle or ellipse with border-radius.

.circle { border-radius: 50%; height: 50px; width: 50px; }

…but more on that later.

Freestyling with SVG paths

Thanks to SVG’s <path> tag, we can create any kind of shape. It is like drawing with a pencil or pen. You start from a point and draw lines, curves, shapes and close the loop.

There are many data parameters in path for different tasks like:

  • M – Moving to the point
  • L – Drawing line
  • C – Drawing a curve
  • Q – Bézier curve
  • Z – Closing the path

Chris has a super thorough guide that explains these parameters in great detail.

We just need the curve (C) parameter for the actual drawing. But we’ll also be moving the starting point and closing the path, so we’ll reach for the M and Z parameters as well.

This is a random blobby shape I put together using SVG’s <path> element.

Ready to break this down? Coordinates play a big role in <path> so what we’re about to look at will look like Google Maps data barfed inside our code. But it makes a lot more sense when we know what they’re doing.

Take this…

<svg xmlns="http://www.w3.org/2000/svg"> <path fill="#24A148" d="" /> </svg>

Here, the d attribute stores the path data. It holds information containing where the drawing starts, what direction it moves, what shape it follows, and where it ends. For example:

<path d="M 10 10 C 20 20, 40 20, 50 10" stroke="black" fill="transparent"/>

It shows that our path starts from coordinates 10 10, indicated by the M that precedes them. Then, it establishes a Cubic Bézier curve (C) with two control points. Bézier curves are like handles on the both ends of a path that control the curviness between them. We have two Bézier “handles”: one for starting position (20 20) of the curve and another for ending position (40 20).

Let’s use this knowledge to design our blob. The blob I drew is actually a bit complex, with a number of curves and control points. It doesn’t help that many of the coordinates aren’t full integers. But, still, now that we know what the <path> ‘s d parameter does and the attributes it uses to draw points along the path, it doesn’t look quite as scary.

CodePen Embed Fallback

But, hey, I get it. That’s a lot of code to not only write by hand, but get exactly right as well. I wouldn’t fault you for using something like this tool to generate the code for you.

Gooey effects with CSS and SVG filters

SVG path is complex. Right? What if I present you a way to convert many custom shapes (which you can create through divs) into gooey blobs? Here’s the idea. We’re going to create two rectangles that intersect. They’re the same color, but have a little transparency to darken where they intersect.

CodePen Embed Fallback

Then we’re going to leverage SVG’s blurring features to smudge the rectangles, creating an extra gooey blob with softer edges. The two intersecting rectangles will turn into this –

Let’s first understand how filters work in SVG. They are declared using <filter> on HTML elements or other SVG elements, like circle.

circle { filter: url("#id_of_filter"); }

<filter> is basically a wrapper for the actual filter effects, that include:

  • <feGaussianBlur>
  • <feImage>
  • <feMerge>
  • <feColorMatrix>
  • Many more… Get the complete list here.

Our blob is blurred and colored, so that’s why we’re going to put <feGaussianBlur> and <feColorMatrix> to use.

<feGaussianBlur> takes multiple attributes, but we are only interested in two of them: how much blur we want and where we want it. The standard deviation (stdDeviation) and in properties align with those needs, respectively.

in accepts one of two values:

  • SourceGraphic – Blurs the entire shape
  • SourceAlpha – Blurs the alpha value, and is used to create shadow effects

After playing around a bit, here’s where I landed on the <feGaussianBlur> effect:

<feGaussianBlur in="SourceGraphic" stdDeviation="30" />

This goes right in the HTML markup with an ID that we call on the parent element of our blob:

<!-- The SVG filter --> <svg style="position: absolute; width: 0; height: 0;"> <filter id="goo"> <feGaussianBlur in="SourceGraphic" stdDeviation="30" /> </filter> </svg> <!-- The blob --> <div class="hooks-main"> <div></div> <div></div> </div>

The filter doesn’t actually render, even though it’s in the markup. Instead, we reference it as a CSS filter on the blob’s parent element:

/* Blob parent element */ .hooks-main { position: absolute; width: 100%; height: 100%; filter: url("#goo&amp"); overflow: hidden; } CodePen Embed Fallback

This isn’t done just yet. The blur is scattered and the element’s shape lost its boundary and color. We need a bulging effect with blur on the boundaries and a solid color to fill the shape. This is where our next SVG filter, <feColorMatrix>, comes into play.

There are two <feColorMatrix> attributes we want:

  • in – Indicates where the effect is applied, just like <feGaussianBlur>.
  • values – A matrix of four rows and five columns.

The values attribute bears a little more nuance. It holds a matrix that gets multiplied with the color and alpha values of each pixel and generates a new color value for that pixel. Mathematically speaking:

new pixel color value = ( values matrix ) × ( current pixel color value )

Let’s get a little numbers nerdy here. In that equation, values matrix is equal to:

[F-red1 F-green1 F-blue1 F-alpha1 F-constant1 F-red2 F-green2 F-blue2 F-alpha2 F-constant2 F-red3 F-green3 F-blue3 F-alpha3 F-constant3 F-red4 F-green4 F-blue4 F-alpha4 F-constant4]

Here, F-red means a fraction of red in pixels, with a value ranging from 0 to 1. F-constant is some constant value to add (or subtract) from color value.

Breaking this down further… We have a color pixel with an RGBA value of rgba(214, 232, 250, 1). To convert it into a new color, we will multiply it with our values matrix.

Values MatrixColor Pixel (RGBA)New Color (RGBA)[1 0 0 0 0
 0 1 0 0 0
 0 0 1 0 0
 0 0 0 1 0
 0 0 0 0 1]×[214
 232
 250
 1
 1]= [ 214x1 + 232x0 + 250x0 + 1x0 + 1x1
      214x0 + 232x1 + 250x0 + 1x0 + 1x1
      214x0 + 232x0 + 250x1 + 1x0 + 1x1
      214x0 + 232x0 + 250x0 + 1x1 + 1x1
      214x0 + 232x0 + 250x0 + 1x0 + 1x1 ]= [214
  232
  250
 1
  1]

The pixel value didn’t change because we multiplied it by the identity matrix, but if you change the values of the matrix, then its pixel value will change too. Learn more about values matrix from MDN documentation.

In our case, these values seem to work pretty well:

<filter id="goo"> <feGaussianBlur in="SourceGraphic" stdDeviation="30" /> <feColorMatrix in="blur" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 30 -7" /> </filter> CodePen Embed Fallback

I’ve added few more styles in the blob to stretch it from the corner.

CodePen Embed Fallback

Try to use these filter values in other shapes and let me know how they work out for you in the comments.

Using CSS border-radius

We teased this earlier, but now let’s get to the CSS border-radius property. It can also create blob-like shape, thanks to it’s ability to smooth out the corners of an element. This is possible because each corner radius is divided into two radii, one for each edge. That’s why we can have more shapes apart from circle and ellipse.

You might be used to using border-radius as a shorthand for all four corners of an element:

.rounded { border-radius: 25%; }

That’s a nice way to get uniformity for all of the corners. But blobs aren’t so uniform. We want some corners to be rounder than others to get some that looks gooey. That’s why we go for the constituent properties of border-radius, like:

.element { border-top-left-radius: 70% 60%; border-top-right-radius: 30% 40%; border-bottom-right-radius: 30% 60%; border-bottom-left-radius: 70% 40%; }

And see how each properties takes two values? That’s one for each edge of the corner, giving us a lot of flexibility to curve an element into interesting shapes. Then we can drop in a background color, fill it up with a gradient, or even set a box-shadow on it to get a neat effect.

CodePen Embed Fallback

The post Three Ways to Blob with CSS and SVG appeared first on CSS-Tricks.

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

Use CSS Variables instead of React Context

Css Tricks - Fri, 02/19/2021 - 6:05am

Turns out you can use several different libraries to pass color information around components. Or, you could use custom properties, built right into CSS, have no decline in your own developer experience, and deliver a faster experience to your users. Kent proves it here, with demos.

For the record, you could go a step further than Kent has here and not use CSS-in-JS at all, but still be updating CSS custom properties from button clicks in React and managing the state there and such. I’m telling ya, one of the main jobs of a UI component library like React is managing state, and CSS might as well know about that state so you can use it to do any styling you need to do.

Wait, not use CSS-in-JS? Kent:

I’ve never been so productive working with CSS than when I added a real programming language to it.

Extreme side eye, Kent.

We should be calling it CSS-in-React, also, since React is the only major framework that doesn’t have a blessed solution for styling.

Direct Link to ArticlePermalink

The post Use CSS Variables instead of React Context appeared first on CSS-Tricks.

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

Mistakes I’ve Made as an Engineering Manager

Css Tricks - Thu, 02/18/2021 - 12:39pm

I’ve been a manager for many years at companies of different scale. Through these experiences, I’ve done my share of learning, and made some mistakes along that way that were important lessons for me. I want to share those with you.

But before diving in, I want to mention a strong caveat that my advice may be unique to my situation because I’m white and a woman in tech. My experiences may be relevant to that point of view, but your mileage may vary.

Another huge caveat: I’m sharing mistakes I’ve made so far in the interest of helping others, but I’m sure I’m not done making mistakes, either. I don’t have it all figured it out, I’m still on this journey.

Credit: WoCinTechChat Mistake 1: Thinking people give feedback the way they want to receive it

Feedback is one of the most important tools you have as a manager, but it can also be incredibly disruptive with poor execution. One of the hardest things I’ve had to learn is that humans aren’t pure functions: an input that works one day and gets one result, then again another day and get an entirely different result.

The same is true of how people give and receive feedback: someone may give you feedback in a particular way, but they prefer to receive much differently when it comes to themselves.

How do you get around this? Asking helps. I’ve started doing an exercise with my team where I ask the group as a whole how they would like to get feedback. Not only does it open up ideas, but it also helps that each individual has to think for themselves how they prefer to receive feedback. Normalizing this type of vulnerability and self-reflection can help us all feel like partners, instead of some top-down edict.

Another thing that’s helped? Asking folks directly in a one-on-one meeting if they have feedback for me as a manager, and following up with an anonymous survey. Again, it makes things feel less one-sided and provides everyone the opportunity to say things that they might not want to say directly to my face, which I know can be tough.

And lastly, if something comes up, addressing it immediately can be helpful. There’s nothing worse than your manager having an issue with something you did and only finding out about it three months later, especially if it’s tied to a performance review that you could have impacted had they been transparent earlier.

The truth is that even my advice here is imperfect. Feedback is tough. Being honest and improving together as a team is awkward. It’s incredibly worth it, though. That’s where the real growth is. That said, no two people are alike, no two groups are alike, and you may have to use your best judgement given the situation at hand.

Mistake 2: Trying to do everything yourself as a manager is the best way to help

Years ago, I managed a woman who was bright, talented, capable, and an all around pleasure. She was sort of new to the industry and could come across as timid, so I did my best to be a poop umbrella for her, fighting battles behind the scenes to set her up for success. She was on a steady track to land a senior role. Even after I decided to leave the company, I let the next manager know this person is track for a senior position in the next few months.

Then I moved to another city. Years later, I met up with the woman and was shocked to learn she never got the position.

Here’s what I learned: her promotion wasn’t the same high priority for the capable hands I left her in as it was for me. The team was challenged with a million other things that took center stage to the extent that her promotion fell off the radar. But even more than that, what became very clear to me was that all of that “protection” I thought I had set up for her didn’t really serve her well for the long haul. For example, I didn’t teach her how to advocate for herself or how to navigate the system. I vowed never to make that mistake again.

This is tough! If you’re strong and care about your team as people, it can feel very unnatural to teach someone to advocate instead of moving things out of their way themselves. And the point is not to throw that person into the fire. The point is to care. Are you teaching the things they need to learn? Are they really growing under you? Feeling like you’re protecting someone at all costs also lead to your own ego trip, too, which threatens progress.

Try to think through what skills someone needs to succeed without you. Teach those things incrementally. Sure, this is easy advice to say, but it’s really hard to do in the thick of things. Spend some time with it, and think through ways you can inject that learning into everyday work and interactions.

Credit: Charles Deluvio on Unsplash Mistake 3: Communicating something one time is enough

No one likes to feel like they’re repeating themselves. It’s annoying to say someone more than once, and it’s annoying to hear something over and again. But if you have a big enough group and there’s enough going on, things are going to slip through the cracks, so repetition becomes an important tool to make things stick. The trick is to say the same things, but in different ways.

There was a time last year when I asked my team to do something and none of them did it. What happened there? Given that it’s a team of highly efficient, strong collaborators, do you think they just all table-flipped and didn’t take action? Not a chance. I was the one who wasn’t clear. In fact, you can probably guess that if a whole group of people don’t understand or take action, the chance is that you, the manager, are the common denominator for why something is blocked. Not only did I not repeat myself enough to be clear, I didn’t align anyone with the why of the purpose of the task. It’s pretty easy to forget or not prioritize doing something if you have no clue why you’re doing it. Repeat yourself and align the group with the importance of the task and you’ll likely have a better result.

Think of all the ways we have to communicate these days: chats, emails, video meetings, texts, document comments, and so much more. And because some people communicate better in one medium than another, using all of the platforms have in various mediums becomes a strategy for repetition without nagging.

I’ve found that what work best is allowing everyone to own the information themselves. For example, if your team practices career laddering, the individual can read aloud each of the ladders in one-on-one and then talk you through their responses to each item. That way, you’re not lecturing — they are owning where they are and what the next steps are as you guide them along.

Mistake 4: You have to have everything together all the time

Some folks think that management looks like a steel fortress of preparedness and authority. I’m not so sure about that.

If something goes wrong, are you more likely to tell the manager acts as though they have everything together all the time, or the manager owns their mistakes? The truth is that your team needs to know you’re human. You can’t fix problems if you don’t know about them, and no one will tell you about them unless you make space for that.

One time, the night before a big release, someone on the team pushed a change that created thousands upon thousands of calls to a service that, in turn, thought it was the target of a DDoS attack, which then shut down our access. Here’s a moment when a lot of folks could have panicked and blamed one another. Instead, we giggled wildly, jumped into chat and on calls, fixed it, and kept going.

I couldn’t have been more proud of the team that day. Their response was wonderful. And it makes all the difference in how we work together, recover, and iterate.

You’re the manager, so if someone is going to show vulnerability first, it’s easiest on team dynamics if it’s you. You can try this by admitting you’re having a bad day, that you don’t understand something, or that made a mistake. You don’t have to do this constantly, a little is helpful.

This is way tougher if you are an underrepresented minority in tech. People will definitely think of an admitted mistake coming from one person as humility and another as failure. I myself struggle with this, too. I think it’s ok to admit that and feel the situation out given your circumstance.

Being a manager is tough. Your mistakes impact people, and that feeling of pressure can be a little isolating. I’ve made all of the mistakes above and more. I feel it’s critical to share so that when we encounter pitfalls, we don’t feel so alone and have a potential path forward.

The post Mistakes I’ve Made as an Engineering Manager appeared first on CSS-Tricks.

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

Recipe websites, data modeling, and user experience

Css Tricks - Thu, 02/18/2021 - 11:19am

Simeon Griggs with some nice UX ideas for a recipe website:

  • No math. Swap between units and adjust servings on-the-fly.
  • Offer alternative ingredients.
  • Re-list the ingredient amounts when they’re referenced in the instructions.

I totally agree, especially on that last one:

Of all our improvements I think this is my favourite.

A typical recipe layout contains ingredients with amounts at the start. Then, a bullet point list of instructions to perform the method.

The method though typically does not reference those amounts again, so if you don’t prepare all your amounts ahead of time (which is what you’re probably supposed to do but come on who does that) you’ll have to keep scanning back and forward.

Part of what makes this stuff possible is how you set up the data model. For example, an ingredient might be an Array instead of a String so that you’re set up for offering alternatives right out of the gate.

Direct Link to ArticlePermalink

The post Recipe websites, data modeling, and user experience appeared first on CSS-Tricks.

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

Let’s Create a Custom Audio Player

Css Tricks - Thu, 02/18/2021 - 6:27am

HTML has a built-in native audio player interface that we get simply using the <audio> element. Point it to a sound file and that’s all there is to it. We even get to specify multiple files for better browser support, as well as a little CSS flexibility to style things up, like giving the audio player a border, some rounded corners, and maybe a little padding and margin.

But even with all that… the rendered audio player itself can look a little, you know, plain.

Did you know it’s possible to create a custom audio player? Of course we can! While the default <audio> player is great in many cases, having a custom player might suit you better, like if you run a podcast and an audio player is the key element on a website for the podcast. Check out the sweet custom player Chris and Dave set up over at the ShopTalk Show website.

The audio player fits in seamlessly with other elements on the page, sporting controls that complement the overall design.

We’re going to take stab at making our own player in this post. So, put on your headphones, crank up some music, and let’s get to work!

The elements of an audio player

First, let’s examine the default HTML audio players that some of the popular browsers provide.

Blink Firefox Internet Explorer

If our goal is to match the functionality of these examples, then we need to make sure our player has:

  • a play/pause button,
  • a seek slider,
  • the current time indicator,
  • the duration of the sound file,
  • a way to mute the audio, and
  • a volume control slider.

Let’s say this is the design we’re aiming for:

We’re not going for anything too fancy here: just a proof of concept sorta thing that we can use to demonstrate how to make something different than what default HTML provides.

Basic markup, styling and scripts for each element

We should first go through the semantic HTML elements of the player before we start building features and styling things. We have plenty of elements to work with here based on the elements we just listed above.

Play/pause button

I think the HTML element appropriate for this button is the <button> element. It will contain the play icon, but the pause icon should also be in this button. That way, we’re toggling between the two rather than taking up space by displaying both at the same time.

Something like this in the markup:

<div id="audio-player-container"> <p>Audio Player</p> <!-- swaps with pause icon --> <button id="play-icon"></button> </div>

So, the question becomes: how do we swap between the two buttons, both visually and functionally? the pause icon will replace the play icon when the play action is triggered. The play button should display when the audio is paused and the pause button should display when the audio is playing.

Of course, a little animation could take place as the icon transitions from the play to pause. What would help us accomplish that is Lottie, a library that renders Adobe After Effects animations natively. We don’t have to create the animation on After Effects though. The animated icon we’re going to use is provided for free by Icons8.

New to Lottie? I wrote up a thorough overview that covers how it works.

In the meantime, permit me to describe the following Pen:

CodePen Embed Fallback

The HTML section contains the following:

  • a container for the player,
  • text that briefly describes the container, and
  • a <button> element for the play and pause actions.

The CSS section includes some light styling. The JavaScript is what we need to break down a bit because it’s doing several things:

// imports the Lottie library via Skypack import lottieWeb from 'https://cdn.skypack.dev/lottie-web'; // variable for the button that will contain both icons const playIconContainer = document.getElementById('play-icon'); // variable that will store the button’s current state (play or pause) let state = 'play'; // loads the animation that transitions the play icon into the pause icon into the referenced button, using Lottie’s loadAnimation() method const animation = lottieWeb.loadAnimation({ container: playIconContainer, path: 'https://maxst.icons8.com/vue-static/landings/animated-icons/icons/pause/pause.json', renderer: 'svg', loop: false, autoplay: false, name: "Demo Animation", }); animation.goToAndStop(14, true); // adds an event listener to the button so that when it is clicked, the the player toggles between play and pause playIconContainer.addEventListener('click', () => { if(state === 'play') { animation.playSegments([14, 27], true); state = 'pause'; } else { animation.playSegments([0, 14], true); state = 'play'; } });

Here’s what the script is doing, minus the code:

  • It imports the Lottie library via Skypack.
  • It references the button that will contain both icons in a variable.
  • It defines a variable that will store the button’s current state (play or pause).
  • It loads the animation that transitions the play icon into the pause icon into the referenced button, using Lottie’s loadAnimation() method.
  • It displays the play icon on load since the audio is initially paused.
  • It adds an event listener to the button so that when it is clicked, the the player toggles between play and pause.
Current time and duration

The current time is like a progress indicate that shows you how much time has elapsed from the start of the audio file. The duration? That’s just how long the sound file is.

A <span> element is okay to display these. The <span> element for the current time, which is to be updated every second, has a default text content of 0:00. On the other side, the one for duration is the duration of the audio in mm:ss format.

<div id="audio-player-container"> <p>Audio Player</p> <button id="play-icon"></button> <span id="current-time" class="time">0:00</span> <span id="duration" class="time">0:00</span> </div> Seek slider and volume control slider

We need a way to move to any point in time in the sound file. So, if I want to skip ahead to the halfway point of the file, I can simply click and drag a slider to that spot in the timeline.

We also need a way to control the sound volume. That, too, can be some sort of click-and-drag slider thingy.

I would say <input type="range"> is the right HTML element for both of these features.

<div id="audio-player-container"> <p>Audio Player</p> <button id="play-icon"></button> <span id="current-time" class="time">0:00</span> <input type="range" id="seek-slider" max="100" value="0"> <span id="duration" class="time">0:00</span> <input type="range" id="volume-slider" max="100" value="100"> </div>

Styling range inputs with CSS is totally possible, but I’ll tell you what: it is difficult for me to wrap my head around. This article will help. Mad respect to you, Ana. Handling browser support with all of those vendor prefixes is a CSS trick in and of itself. Look at all the code needed on input[type="range"] to get a consistent experience:

input[type="range"] { position: relative; -webkit-appearance: none; width: 48%; margin: 0; padding: 0; height: 19px; margin: 30px 2.5% 20px 2.5%; float: left; outline: none; } input[type="range"]::-webkit-slider-runnable-track { width: 100%; height: 3px; cursor: pointer; background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width)); } input[type="range"]::before { position: absolute; content: ""; top: 8px; left: 0; width: var(--seek-before-width); height: 3px; background-color: #007db5; cursor: pointer; } input[type="range"]::-webkit-slider-thumb { position: relative; -webkit-appearance: none; box-sizing: content-box; border: 1px solid #007db5; height: 15px; width: 15px; border-radius: 50%; background-color: #fff; cursor: pointer; margin: -7px 0 0 0; } input[type="range"]:active::-webkit-slider-thumb { transform: scale(1.2); background: #007db5; } input[type="range"]::-moz-range-track { width: 100%; height: 3px; cursor: pointer; background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width)); } input[type="range"]::-moz-range-progress { background-color: #007db5; } input[type="range"]::-moz-focus-outer { border: 0; } input[type="range"]::-moz-range-thumb { box-sizing: content-box; border: 1px solid #007db5; height: 15px; width: 15px; border-radius: 50%; background-color: #fff; cursor: pointer; } input[type="range"]:active::-moz-range-thumb { transform: scale(1.2); background: #007db5; } input[type="range"]::-ms-track { width: 100%; height: 3px; cursor: pointer; background: transparent; border: solid transparent; color: transparent; } input[type="range"]::-ms-fill-lower { background-color: #007db5; } input[type="range"]::-ms-fill-upper { background: linear-gradient(to right, rgba(0, 125, 181, 0.6) var(--buffered-width), rgba(0, 125, 181, 0.2) var(--buffered-width)); } input[type="range"]::-ms-thumb { box-sizing: content-box; border: 1px solid #007db5; height: 15px; width: 15px; border-radius: 50%; background-color: #fff; cursor: pointer; } input[type="range"]:active::-ms-thumb { transform: scale(1.2); background: #007db5; }

Whoa! What does even mean, right?

Styling the progress section of range inputs is a tricky endeavor. Firefox provides the ::-moz-range-progress pseudo-element while Internet Explorer provides ::-ms-fill-lower. As WebKit browsers do not provide any similar pseudo-element, we have to use the ::before pseudo-element to improvise the progress. That explains why, if you noticed, I added event listeners in the JavaScript section to set custom CSS properties (e.g. --before-width) that update when the input event is fired on each of the sliders.

One of the native HTML <audio> examples we looked at earlier shows the buffered amount of the audio. The --buffered-width property specifies the amount of the audio, in percentage, that the user can play through to without having to wait for the browser to download. I imitated this feature with the linear-gradient() function on the track of the seek slider. I used the rgba() function in the linear-gradient() function for the color stops to show transparency. The buffered width has a much deeper color compared to the rest of the track. However, we would treat the actual implementation of this feature much later.

Volume percentage

This is to display the percentage volume. The text content of this element is updated as the user changes the volume through the slider. Since it is based on user input, I think this element should be the <output> element.

<div id="audio-player-container"> <p>Audio Player</p> <button id="play-icon"></button> <span id="current-time" class="time">0:00</span> <input type="range" id="seek-slider" max="100" value="0"> <span id="duration" class="time">0:00</span> <output id="volume-output">100</output> <input type="range" id="volume-slider" max="100" value="100"> </div> Mute button

Like for the play and pause actions, this should be in a <button> element. Luckily for us, Icons8 also has an animated mute icon. So we would use the Lottie library here just as we did for the play/pause button.

<div id="audio-player-container"> <p>Audio Player</p> <button id="play-icon"></button> <span id="current-time" class="time">0:00</span> <input type="range" id="seek-slider" max="100" value="0"> <span id="duration" class="time">0:00</span> <output id="volume-output">100</output> <input type="range" id="volume-slider" max="100" value="100"> <button id="mute-icon"></button> </div>

That’s all of the basic markup, styling and scripting we need at the moment!

CodePen Embed Fallback Working on the functionality

The HTML <audio> element has a preload attribute. This attribute gives the browser instructions for how to load the audio file. It accepts one of three values:

  • none – indicates that the browser should not load the audio at all (unless the user initiates the play action)
  • metadata – indicates that only the metadata (like length) of the audio should be loaded
  • auto – loads the complete audio file

An empty string is equivalent to the auto value. Note, however, that these values are merely hints to the browser. The browser does not have to agree to these values. For example, if a user is on a cellular network on iOS, Safari does not load any part of an audio, regardless of the preload attribute, except the user triggers the play action. For this player, we would use the metadata value since it doesn’t require much overhead and we want to display the length of the audio.

What would help us accomplish the features our audio player should have is the JavaScript HTMLMediaElement interface, which the HTMLAudioElement interface inherits. For our audio player code to be as self-explanatory as possible, I’d divide the JavaScript into two sections: presentation and functionality.

First off, we should create an <audio> element in the audio player that has the basic features we want:

<div id=”audio-player-container”> <audio src=”my-favourite-song.mp3” preload=”metadata” loop> <button id="play-icon"></button> <!-- ... --> </div> Display the audio duration

The first thing we want to display on the browser is the duration of the audio, when it is available. The HTMLAudioElement interface has a duration property, which returns the duration of the audio, returned in seconds units. If it is unavailable, it returns NaN.

We’ve set preload to metadata in this example, so the browser should provide us that information up front on load… assuming it respects preload. Since we’d be certain that the duration will be available when the browser has downloaded the metadata of the audio, we display it in our handler for the loadedmetadata event, which the interface also provides:

const audio = document.querySelector('audio'); audio.addEventListener('loadedmetadata', () => { displayAudioDuration(audio.duration); });

That’s great but, again, we get the duration in second. We probably should convert that to a mm:ss format:

const calculateTime = (secs) => { const minutes = Math.floor(secs / 60); const seconds = Math.floor(secs % 60); const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`; return `${minutes}:${returnedSeconds}`; }

We’re using Math.floor() because the seconds returned by the duration property typically come in decimals.

The third variable, returnedSeconds, is necessary for situations where the duration is something like 4 minutes and 8 seconds. We would want to return 4:08, not 4:8.

More often than not, the browser loads the audio faster than usual. When this happens, the loadedmetadata event is fired before its listener can be added to the <audio> element. Therefore, the audio duration is not displayed on the browser. Nevertheless, there’s a hack. The HTMLMediaElement has a property called readyState. It returns a number that, according to MDN Web Docs, indicates the readiness state of the media. The following describes the values:

  • 0 – no data about the media is available.
  • 1 – the metadata attributes of the media are available.
  • 2 – data is available, but not enough to play more than a frame.
  • 3 – data is available, but for a little amount of frames from the current playback position.
  • 4 – data is available, such that the media can be played through to the end without interruption.

We want to focus on the metadata. So our approach is to display the duration if the metadata of the audio is available. If it is not available, we add the event listener. That way, the duration is always displayed.

const audio = document.querySelector('audio'); const durationContainer = document.getElementById('duration'); const calculateTime = (secs) => { const minutes = Math.floor(secs / 60); const seconds = Math.floor(secs % 60); const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`; return `${minutes}:${returnedSeconds}`; } const displayDuration = () => { durationContainer.textContent = calculateTime(audio.duration); } if (audio.readyState > 0) { displayDuration(); } else { audio.addEventListener('loadedmetadata', () => { displayDuration(); }); } Seek slider

The default value of the range slider’s max property is 100. The general idea is that when the audio is playing, the thumb is supposed to be “sliding.” Also, it is supposed to move every second, such that it gets to the end of the slider when the audio ends.

Notwithstanding, if the audio duration is 150 seconds and the value of the slider’s max property is 100, the thumb will get to the end of the slider before the audio ends. This is why it is necessary to set the value of the slider’s max property to the audio duration in seconds. This way, the thumb gets to the end of the slider when the audio ends. Recall that this should be when the audio duration is available, when the browser has downloaded the audio metadata, as in the following:

const seekSlider = document.getElementById('seek-slider'); const setSliderMax = () => { seekSlider.max = Math.floor(audio.duration); } if (audio.readyState > 0) { displayDuration(); setSliderMax(); } else { audio.addEventListener('loadedmetadata', () => { displayDuration(); setSliderMax(); }); } Buffered amount

As the browser downloads the audio, it would be nice for the user to know how much of it they can seek to without delay. The HTMLMediaElement interface provides the buffered and seekable properties. The buffered property returns a TimeRanges object, which indicates the chunks of media that the browser has downloaded. According to MDN Web Docs, a TimeRanges object is a series of non-overlapping ranges of time, with start and stop times. The chunks are usually contiguous, unless the user seeks to another part in the media. The seekable property returns a TimeRanges object, which indicates “seekable” parts of the media, irrespective of whether they’ve been downloaded or not.

Recall that the preload="metadata" attribute is present in our <audio> element. If, for example the audio duration is 100 seconds, the buffered property returns a TimeRanges object similar to the following:

When the audio has started playing, the seekable property would return a TimeRanges object similar to the following:

It returns multiple chunks of media because, more often than not, byte-range requests are enabled on the server. What this means is that multiple parts of the media can be downloaded simultaneously. However, we want to display the buffered amount closest to the current playback position. That would be the first chunk (time range 0 to 20). That would be the first and last chunk from the first image. As the audio starts playing, the browser begins to download more chunks. We would want to display the one closest to the current playback position, which would be the current last chunk returned by the buffered property. The following snippet would store in the variable, bufferedAmount, i.e. the time for the end of the last range in the TimeRanges object returned by the buffered property.

const audio = document.querySelector('audio'); const bufferedAmount = audio.buffered.end(audio.buffered.length - 1);

This would be 20 from the 0 to 20 range in the first image. The following snippet stores in the variable, seekableAmount, the time for the end of the last range in the TimeRanges object returned by the seekable property.

const audio = document.querySelector('audio'); const seekableAmount = audio.seekable.end(audio.seekable.length - 1);

Nevertheless, this would be 100 from the 90 to 100 range in the second image, which is the entire audio duration. Note that there are some holes in the TimeRanges object as the browser only downloads some parts of the audio. What this means is that the entire duration would be displayed to the user as the buffered amount. Meanwhile, some parts in the audio are not available yet. Because this won’t provide the best user experience, the first snippet is what we should use.

As the browser downloads the audio, the user should expect that the buffered amount on the slider increases in width. The HTMLMediaElement provides an event, the progress event, which fires as the browser loads the media. Of course, I’m thinking what you’re thinking! The buffered amount should be incremented in the handler for the audio’s progress event.

Finally, we should actually display the buffered amount on the seek slider. We do that by setting the property we talked about earlier, --buffered-width, as a percentage of the value of the slider’s max property. Yes, in the handler for the progress event too. Also, because of the browser loading the audio faster than usual, we should update the property in the loadedmetadata event and its preceding conditional block that checks for the readiness state of the audio. The following Pen combines all that we’ve covered so far:

CodePen Embed Fallback Current time

As the user slides the thumb along the range input, the range value should be reflected in the <span> element containing the current time of the audio. This tells the user the current playback position of the audio. We do this in the handler of the slider’s input event listener.

If you think the correct event to listen to should be the change event, I beg to differ. Say the user moved the thumb from value 0 to 20. The input event fires at values 1 through to 20. However, the change event will fire only at value 20. If we use the change event, it will not reflect the playback position from values 1 to 19. So, I think the input event is appropriate. Then, in the handler for the event, we pass the slider’s value to the calculateTime() function we defined earlier.

We created the function to take time in seconds and return it in a mm:ss format. If you’re thinking, Oh, but the slider’s value is not time in seconds, let me explain. Actually, it is. Recall that we set the value of the slider’s max property to the audio duration, when it is available. Let’s say the audio duration is 100 seconds. If the user slides the thumb to the middle of the slider, the slider’s value will be 50. We wouldn’t want 50 to appear in the current time box because it is not in accordance with the mm:ss format. When we pass 50 to the function, the function returns 0:50 and that would be a better representation of the playback position.

I added the snippet below to our JavaScript.

const currentTimeContainer = document.getElementById('current-time'); seekSlider.addEventListener('input', () => { currentTimeContainer.textContent = calculateTime(seekSlider.value); });

To see it in action, you can move the seek slider’s thumb back and forth in the following Pen:

CodePen Embed Fallback Play/pause

Now we’re going to set the audio to play or pause according to the respective action triggered by the user. If you recall, we created a variable, playState, to store the state of the button. That variable is what will help us know when to play or pause the audio. If its value is play and the button is clicked, our script is expected to perform the following actions:

  • play the audio
  • change the icon from play to pause
  • change the playState value to pause

We already implemented the second and third actions in the handler for the button’s click event. What we need to do is to add the statements to play and pause the audio in the event handler:

playIconContainer.addEventListener('click', () => { if(playState === 'play') { audio.play(); playAnimation.playSegments([14, 27], true); playState = 'pause'; } else { audio.pause(); playAnimation.playSegments([0, 14], true); playState = 'play'; } });

It is possible that the user will want to seek to a specific part in the audio. In that case, we set the value of the audio’s currentTime property to the seek slider’s value. The slider’s change event will come in handy here. If we use the input event, various parts of the audio will play in a very short amount of time.

Recall our scenario of 1 to 20 values. Now imagine the user slides the thumb from 1 to 20 in, say, two seconds. That’s 20 seconds audio playing in two seconds. It’s like listening to Busta Rhymes on 3× speed. I’d suggest we use the change event. The audio will only play after the user is done seeking. This is what I’m talking about:

seekSlider.addEventListener('change', () => { audio.currentTime = seekSlider.value; });

With that out of the way, something needs to be done while the audio is playing. That is to set the slider’s value to the current time of the audio. Or move the slider’s thumb by one tick every second. Since the audio duration and the slider’s max value are the same, the thumb gets to the end of the slider when the audio ends. Now the timeupdate event of the HTMLMediaElement interface should be the appropriate event for this. This event is fired as the value of the media’s currentTime property is updated, which is approximately four times in one second. So in the handler for this event, we could set the slider’s value to the audio’s current time. This should work just fine:

audio.addEventListener('timeupdate', () => { seekSlider.value = Math.floor(audio.currentTime); });

However, there are some things to take note of here:

  1. As the audio is playing, and the seek slider’s value is being updated, a user is unable to interact with the slider. If the audio is paused, the slider won’t be able to receive input from the user because it is constantly being updated.
  2. In the handler, we update the value of the slider but its input event does not fire. This is because the event only fires when a user updates the slider’s value on the browser, and not when it is updated programmatically.

Let’s consider the first issue.

To be able to interact with the slider while the audio is playing, we would have to pause the process of updating it’s value when it receives input. Then, when the slider loses focus, we resume the process. But, we don’t have access to this process. My hack would be to use the requestAnimationFrame() global method for the process. But this time, we won’t be using the timeupdate event for this because it still won’t work. The animation would play forever until the audio is paused, and that’s not what we want. Therefore, we use the play/pause button’s click event.

To use the requestAnimationFrame() method for this feature, we have to accomplish these steps:

  1. Create a function to keep our “update slider value” statement.
  2. Initialize a variable in the function that was previously created to store the request ID returned by the function (that will be used to pause the update process).
  3. Add the statements in the play/pause button click event handler to start and pause the process in the respective blocks.

This is illustrated in the following snippet:

let rAF = null; const whilePlaying = () => { seekSlider.value = Math.floor(audio.currentTime); rAF = requestAnimationFrame(whilePlaying); } playIconContainer.addEventListener('click', () => { if(playState === 'play') { audio.play(); playAnimation.playSegments([14, 27], true); requestAnimationFrame(whilePlaying); playState = 'pause'; } else { audio.pause(); playAnimation.playSegments([0, 14], true); cancelAnimationFrame(rAF); playState = 'play'; } });

But this doesn’t exactly solve our problem. The process is only paused when the audio is paused. We also need to pause the process, if it is in execution (i.e. if the audio is playing), when the user wants to interact with the slider. Then, after the slider loses focus, if the process was ongoing before (i.e. if the audio was playing), we start the process again. For this, we would use the slider’s input event handler to pause the process. To start the process again, we would use the change event because it is fired after the user is done sliding the thumb. Here is the implementation:

seekSlider.addEventListener('input', () => { currentTimeContainer.textContent = calculateTime(seekSlider.value); if(!audio.paused) { cancelAnimationFrame(raf); } }); seekSlider.addEventListener('change', () => { audio.currentTime = seekSlider.value; if(!audio.paused) { requestAnimationFrame(whilePlaying); } });

I was able to come up with something for the second issue. I added the statements in the seek slider’s input event handlers to the whilePlaying() function. Recall that there are two event listeners for the slider’s input event: one for the presentation, and the other for the functionality. After adding the two statements from the handlers, this is how our whilePlaying() function looks:

const whilePlaying = () => { seekSlider.value = Math.floor(audio.currentTime); currentTimeContainer.textContent = calculateTime(seekSlider.value); audioPlayerContainer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`); raf = requestAnimationFrame(whilePlaying); }

Note that the statement on the fourth line is the seek slider’s appropriate statement from the showRangeProgress() function we created earlier in the presentation section.

Now we’re left with the volume-control functionality. Whew! But before we begin working on that, here’s a Pen covering all we’ve done so far:

CodePen Embed Fallback Volume-control

For volume-control, we’re utilizing the second slider, #volume-slider. When the user interacts with the slider, the slider’s value is reflected in the volume of the audio and the <output> element we created earlier.

The slider’s max property has a default value of 100. This makes it easy to display its value in the <output> element when it is updated. We could implement this in the input event handler of the slider. However, to implement this in the volume of the audio, we’re going to have to do some math.

The HTMLMediaElement interface provides a volume property, which returns a value between 0 and 1, where 1 being is the loudest value. What this means is if the user sets the slider’s value to 50, we would have to set the volume property to 0.5. Since 0.5 is a hundredth of 50, we could set the volume to a hundredth of the slider’s value.

const volumeSlider = document.getElementById('volume-slider'); const outputContainer = document.getElementById('volume-output'); volumeSlider.addEventListener('input', (e) => { const value = e.target.value; outputContainer.textContent = value; audio.volume = value / 100; });

Not bad, right?

Muting audio

Next up is the speaker icon, which is clicked to mute and unmute the audio. To mute the audio, we would use its muted property, which is also available via HTMLMediaElement as a boolean type. Its default value is false, which is unmuted. To mute the audio, we set the property to true. If you recall, we added a click event listener to the speaker icon for the presentation (the Lottie animation). To mute and unmute the audio, we should add the statements to the respective conditional blocks in that handler, as in the following:

const muteIconContainer = document.getElementById('mute-icon'); muteIconContainer.addEventListener('click', () => { if(muteState === 'unmute') { muteAnimation.playSegments([0, 15], true); audio.muted = true; muteState = 'mute'; } else { muteAnimation.playSegments([15, 25], true); audio.muted = false; muteState = 'unmute'; } }); Full demo

Here’s the full demo of our custom audio player in all its glory!

CodePen Embed Fallback

But before we call it quits, I’d like to introduce something — something that will give our user access to the media playback outside of the browser tab where our custom audio player lives.

Permit me to introduce to you, drumroll, please…

The Media Session API

Basically, this API lets the user pause, play, and/or perform other media playback actions, but not with our audio player. Depending on the device or the browser, the user initiates these actions through the notification area, media hubs, or any other interface provided by their browser or OS. I have another article just on that for you to get more context on that.

The following Pen contains the implementation of the Media Session API:

CodePen Embed Fallback

If you view this Pen on your mobile, take a sneak peek at the notification area. If you’re on Chrome on your computer, check the media hub. If your smartwatch is paired, I’d suggest you look at it. You could also tell your voice assistant to perform some of the actions on the audio. Ten bucks says it’ll make you smile. &#x1f913;

One more thing…

If you need an audio player on a webpage, there’s a high chance that the page contains other stuff. That’s why I think it’s smart to group the audio player and all the code needed for it into a web component. This way, the webpage possesses a form of separation of concerns. I transferred everything we’ve done into a web component and came up with the following:

CodePen Embed Fallback

Wrapping up, I’d say the possibilities of creating a media player are endless with the HTMLMediaElement interface. There’s so many various properties and methods for various functions. Then there’s the Media Session API for an enhanced experience.

What’s the saying? With great power comes great responsibility, right? Think of all the various controls, elements, and edge cases we had to consider for what ultimately amounts to a modest custom audio player. Just goes to show that audio players are more than hitting play and pause. Properly speccing out functional requirements will definitely help plan your code in advance and save you lots of time.

The post Let’s Create a Custom Audio Player appeared first on CSS-Tricks.

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

Barebones CSS for Fluid Images

Css Tricks - Thu, 02/18/2021 - 6:25am

Zach takes a look at some fundamental HTML+CSS usage for fluid, responsive images. Most of it, I’d say, is what you’d expect, but things get weird when srcset gets involved.

I poked my way through, and in addition to the weird thing Zach noted, wanted to add one more thing. Let’s start like this:

<img src="./img.jpg" alt="" />

With no other CSS involved, this renders at the “intrinsic size” of the image. Say the original image is 400px wide, it renders 400px wide.

We should be putting width and height attributes on images, because it allows the browser to make space for them even before they are downloaded (even when they are fluid, which is super cool). So:

<img src="./img.jpg" alt="" width="400" height="300" />

Also nothing terribly weird there. Even if we slap max-width: 100% in the CSS, that’ll do what we want: preserving space, behave fluidly, and not growing bigger than it should.

But let’s hold off on the max-width: 100% thing for a second. If we just use srcset and set up multiple sources.

<img src="./img.jpg" alt="" srcset="./img-200.jpg 200w, ./img-400.jpg 400w" />

BAM, we blow out the width of the thing.

That won’t render at 200px or 400px—it’ll actually render at 100vw, believe it or not. I think that’s because that’s the default sizes value. I normally think of the sizes attribute as not information about anything to do with actual layout, but just information for the browser to choose a source. But that’s not true here. It really does effect layout (in all browsers I tested). Here’s proof:

CodePen Embed Fallback

See the little one below it where all I change is the sizes.

Anyway that’s not what Zach honed in on, but it’s similar. Let’s put back the responsible thing and add in width and height attributes.

<img src="./img.jpg" alt="" width="200" height="137" srcset="./img-200.jpg 200w, ./img-400.jpg 200w" />

No more blowout (with or without sizes) but now we have a new weird problem. This is basically like saying max-width: 200px. Even though we have sources that are wider than 200px, we’ve capped the width at 200px. Zach puts it like:

Using max-width: 100% constrains the image to the container, but be careful when you use this with srcset—it may cap smaller than you want when using [width]! Pair with width: auto to fix this.

Zach’s final snippet is this, which I think reigns in all the weirdness:

img { max-width: 100%; } img[width] { width: auto; /* Defer to max-width */ } img[width][height] { height: auto; /* Preserve aspect ratio */ } /* Let SVG scale without boundaries */ img[src$=".svg"] { width: 100%; height: auto; max-width: none; }

Direct Link to ArticlePermalink

The post Barebones CSS for Fluid Images appeared first on CSS-Tricks.

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

Progressive enhancement and accessibility

QuirksBlog - Thu, 02/18/2021 - 1:29am

This article asks a question I don’t know the answer to: What is the exact relationship between progressive enhancement and accessiblity?

I mean, there is considerable overlap between the two. Good progressive enhancement can help accessibility, while accessibility can guide progressive enhancement decisions.

When I created the progressive enhancement reading list for my PE course in March I asked for good articles. I got a few submissions that I eventually rejected because they were about an accessibility problem that isn’t (quite) PE. Still, these submissions indicate that PE problems can be confused with accessibility ones. We instinctively we feel there’s considerable overlap between the two.

Still, they are not the same. You can have an thorny progressive enhancement problem that poses no accessibility problems, and you can have an accessibility problem that bears no relation to progressive enhancement.

The problem is that I can’t quite put my finger on where progressive enhancement and accessibility meet. Well, they can meet in individual problems, but that’s not what I mean. I’m looking for serious theoretical thought, and so far I haven’t found any. Also, my brain refuses to throw out a workable definition and stays stubbornly silent.

So can anyone define the relationship between progressive enhancement and accessibility? You can reach me via Twitter or my contact form.

Progressive Enhancement reading list 2021

QuirksBlog - Thu, 02/18/2021 - 1:23am

In March I am going to teach the Progressive Enhancement course of the Web minor at university for the third time. I decided to expand the reading list for this course, and here I present the version I’m going to use in 2021.

img { max-width: 100%; } Defining progressive enhancement

Let’s start at the original definition of progressive enhancement.

In 2008 Aaron Gustafson published Understanding Progressive Enhancement at A List Apart, and placed progressive enhancement at the forefront of web developer thinking. Aaron did not invent the concept — he points to prior art (slides) by Steve Champeon and Nick Finck. Still, Aaron’s article popularised the concept.

Aaron compares progressive enhancement to its precursor graceful degradation and finds that PE is the better approach — something that has become generally accepted since then. He also described progressive enhancement comprehensively, and we essentially still follow his definition.

Chris Taylor sees progressive enhancement as technical credit, the opposite of the technical debt you incur when you quickly insert some hacks to get the system to work and solemnly resolve to fix them “later.” (Hint: later never comes.) PE is the opposite: it prevents problems from arising, and thus saves you time in the future. The article also contains a useful overview of progressive enhancement principles.

Progressive enhancement also helps you combat browser incompatibilities. Justin Crawford, Chris Mills, and Ali Spivak make the web work for everyone by addressing cross-browser problems and their causes (which mostly come down to web developers not quite knowing what they’re doing). Better browser compatibility leads to better accessibility, and also to better results, since users will switch sites if they encounter problems. The best way to get these results is to practice PE. (And there we go again: PE and accessibility are clearly related. But how exactly?)

Their browser market share notes are worth repeating. Although Chrome is the largest browser, in January 2021 it still has only 63% of the market according to StatCounter. That sounds like a lot, but it means 37% of your users do not use Chrome. Don’t leave them out in the cold.

Does this sound theoretical? Let’s get practical. Robin Whittleton explains why we use progressive enhancement to build GOV.UK and walks you through the decisions. This is still a high-level overview, but it was actually used in an actual major website. We’ll see gov.uk in action later in this reading list.

Progressive enhancement and UX

The Nielsen Norman Group discusses the role of enhancement in web design and shows that progressive enhancement is useful in non-technical contexts as well. Where the previous articles focused on technical issues, this one gives a good theoretical overview of PE from a UX perspective.

What is progressive enhancement’s purpose in user interface design, and how do you decide which functionalities should be progressively enhanced? The article offers a few hardware examples, for instance the mouse wheel, which was a progressive enhancement when it was introduced, and still is, because touchscreen devices as well as keypads lack a wheel (and, in fact, a mouse). Input modes are ruled by PE, too.

Two excellent general rules are worth quoting in full:

  1. Don’t add other enhancements that provide the same functionality. [...] You want to give people the chance to practice and strengthen the enhancement; if you add other enhancements for the same interface functionality, it will be less likely that any one of them will get enough use.
  2. Be consistent. Use the same enhancement everywhere you can. That is, try to give users many opportunities to practice and thus strengthen the association between the enhancement and its effect in the interface. (Remember, repetition is the mother of retention.) Ideally, designers should use the same enhancements across many different sites, to allow people to learn them.

Aaron Walter created the Hierarchy of User Needs model, which forms the basis of a theory of user delight: why usability is the foundation for delightful experiences, also by the Nielsen Norman Group (image below borrowed from this article).

Delight is all very well, but without a solid foundation of usability, reliability, and functionality it falls flat. If something looks gorgeous but is incomprehensible, doesn’t always work, or doesn’t work at all, it is useless. The relationship between the four layers of user needs is pure progressive enhancement: the next layer is only useful if the layers below it work, and for each functionality you have to decide in which layer(s) to put it.

The PE layers

Let’s return to the technical aspects of progressive enhancement.

In order to progressively enhance a site you first need to define its core functionality. As Andy Bell says, a minimum viable experience makes for a resilient, inclusive website or app. He argues that porting the idea of a minimum viable product to the website experience is a good starting point for your PE project. Which core functionalities are required to give any user the opportunity to finish the task at hand? How do we identify a minimum viable experience, and how do we layer JavaScript functionalities on top of them?

Speaking of layers, Hidde de Vries explains why it's good for users that HTML, CSS and JS are separate languages. He argues that separation of concerns between structure, presentation, and behaviour remains a good thing. This impacts progressive enhancement by forcing you to think about which functionalities you should implement in which layer(s).

So let’s go through the layers.

Layer 1: HTML

Terence Eden discusses the unreasonable effectiveness of simple HTML by telling a story about a user being forced to work on a government-related task on the PlayStation browser (which is — let’s call it not good and leave it at that). The user managed to do what she set out because the site she needed had a simple, good HTML structure that works in any browser. This is what core functionality and minimum viable experience are all about. And you just need HTML to do it.

Dave Rupert created an indispensable list of HTML: the inaccessible parts, where he gives a round-up of accessibility problems with HTML elements. If you want to use any of these HTML elements you should apply the principles of progressive enhancement to make sure they work everywhere. This shows that HTML is not necessarily restricted to the lowest, functional layer but can also enhance (or detract from) the reliable, functional, and pleasurable layers. (Also, it shows yet again there is a close relationship between progressive enhancement and accessibility.)

Léonie Watson wrote a short note on progressive ARIA where she shows that changing the role of an element (here a link to a button; why?; but this happens all the time) also means you should make sure users can click it with the Space key. This is possible for buttons, but not for links, and if you change a link to a button the browser doesn’t automatically add the Space key. So you have to progressively enhance it.

Layer 2: CSS

I have not been able to find specific articles about CSS and progressive enhancement, although they must be out there. I’ll update this section when I find any.

Layer 3: JavaScript

Then we come to the elephant in the room: JavaScript. I mean, everyone has JavaScript, right? As Stuart Langridge shows, this is untrue. Even if the user doesn’t disable JavaScript explicitly there may be many reasons why they don’t have JavaScript.

Incidentally, measuring the number of users who turn off JavaScript is very easy. Just tweet something like “No one turns off JavaScript anyway,” wait for about a day for people to tell you in no uncertain terms they do in fact turn off JavaScript, count these reactions, and you know how many people turn off JavaScript.

Given that JavaScript is a progressive enhancement challenge, not only because it can be absent but also because “modern” web development uses such an incredible amount of it, Jeremy Keith’s 2014 call to be progressive remains relevant today. This article summarises an interesting discussion from those days and contains a lot of excellent points about how to view progressive enhancement, browsers, JavaScript, and more.

Jeremy calls for more server-side components:

Personally, I try not to completely reinvent all the business logic that I’ve already figured out on the server, and then rewrite it all in JavaScript. I prefer to use JavaScript—and specifically Ajax—as a dumb waiter, shuffling data back and forth between the client and server, where the real complexity lies.

I also think that building in this way will take longer …at first. But then on the next project, it takes less time. And on the project after that, it takes less time again. From that perspective, it’s similar to switching from tables for layout to using CSS, or switching from building fixed-with sites to responsive design: the initial learning curve is steep, but then it gets easier over time, until it simply becomes normal.

Did anyone listen to him in the years since 2014? (Hint: no.)

Chris James gives a quick overview of the past web, when things were still good, and describes the Web I Want. Then he gives a useful overview of why we don’t need that much JavaScript in our pages: HTML is already perfectly suited for showing content pages.

Finally, Thomas Steiner explains how to progressively enhance your Progressive Web App by digging into layers of JavaScript support in an advanced article. Assuming JavaScript is present, he gives an example where a simple but insufficient JavaScript is enhanced when the browser supports the File System Access API. He then gives a few other examples of modern APIs and how to feature-detect them. This is on a site by the Chrome devrel team, so it’s Chrome-centric in the features it treats, but the techniques Thomas teaches are applicable anywhere.

Practical examples

Jim Nielsen shows how he is progressively enhancing a small widget. This is a simple, first PE mini-project that is well suited to understand the basic concepts. He uses JavaScript to progressively enhance a static page, and the key takeaway is how the script changes the page’s static content.

Andy Bell (again) studies the power of progressive enhancement. He discusses a (no longer existing) web app in PE terms: start with the core functionality, then layer extras on top. Contains an excellent, simple bit of advice on how to handle the fact that some browsers don’t support CSS grid. This article highlights practical PE decisions and how they work.

Chris Scott created a practical Progressive Enhancement and Data Visualizations example project where he progressively enhances a timeline by first creating a solid HTML structure, then adds some presentational CSS, and then layers JavaScript and SVG on top that changes the presentation considerably.

That’s it. That was the reading list.

If you know of more good articles for the next version you can reach me via Twitter or my contact form.

You want…

Css Tricks - Wed, 02/17/2021 - 11:50am

I’ve been enjoying these little “You want…” style posts. Post titles like that are a little more… forceful for my normal taste, but I like the spirit of sharing a best practice that perhaps isn’t well-known-enough.

Got an idea along these lines? You should blog it! Here or elsewhere.

The post You want… appeared first on CSS-Tricks.

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

Things You Can Do With CSS Today

Css Tricks - Wed, 02/17/2021 - 11:20am

Some nice coverage from Andy about CSS things that are truly new. If you haven’t looked at new things in CSS in, say, a year, I’d bet pretty much all of this will be new to you. A lot of it is cutting-edge enough that you might not be able to get it into projects immediately, but that gap is getting pretty short these days. Rough guess, I’d say a year and we’ll be using all this stuff without much thought.

  • Masonry layout (e.g. grid-template-rows: masonry;) which I think was a terribly clever way to approach this long-awaited feature..
  • The :is selector which makes certain selectors way less obnoxious to write (e.g. article :is(h1, h2, h3):not(:first-child)). This makes me wonder why we never had such a thing in Sass that helped with that.
  • Functions like min(), max(), and clamp(), and I think the best practices and clever uses for them are just shaking out. Fluid type is the most obvious and useful example, but only scratches the surface.
  • Units like ch and ex. I really like max-width: 70ch;. There’s a general bit of typography advice that line length should be between 45 and 75 characters long (I made a bookmarklet to test it once), so rather than forcing that with some abstractly related width, you use the actual width of characters as the width.
  • Fancy text-decoration (e.g. text-decoration-thickness: 0.5rem;) meaning we can thicken up an underline without giving up the usefulness that is text-decoration-skip-ink like we would if we had to resort to a border.)

Direct Link to ArticlePermalink

The post Things You Can Do With CSS Today appeared first on CSS-Tricks.

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

CSS Switch-Case Conditions

Css Tricks - Wed, 02/17/2021 - 6:05am

CSS is yet to have a switch rule or conditional if, aside from the specific nature of @media queries and some deep trickery with CSS custom properties. Let’s have a look at why it would be useful if we did, and look at a trick that is usable today for pulling it off.

Recent chatter about the possibility

While none of these things are usable today, there has been a good amount of chat about the concept of generic conditional CSS just in the last year:

So, yes. The demand for conditional CSS is there.

Imagine why conditional CSS would be useful

Perhaps a visual change after a certain amount of scrolling. A visual change after a numeric input is within a certain range. A component with a handful of states.

There is a whole genre of extremely popular JavaScript libraries for UI (e.g. React, Vue, etc.) that are essentially for building UI based on state. Clearly this is a developer need. If we could move that state-based styling to CSS, that’s all the less JavaScript we might need — and maybe a better separation of concerns.

A common theme

We already have custom properties in CSS, and we could base state-change logic on them, changing a block of styles as a side effect of the custom property changing to certain values.

It’s true that we have mechanisms for changing blocks of styles already. We can change class through JavaScript, and that class can apply whatever we like in CSS. But that doesn’t mean state-based styling in CSS wouldn’t be useful. We don’t always have the ability or may not want to write any JavaScript for this, and instead change custom properties in other ways (e.g. media queries, HTML changes, etc). Doing it in CSS means helping separate business logic and visual style logic.

A trick! Using @keyframes for state

CSS @keyframes can be used to switch specific changes. Through the power of the animation property, a possibility opens up to select exactly which frame to show, and have it pause exactly on that frame, effectively mimicking a switch-case statement or state-based styles.

Let’s see see this in action by playing with the animation-delay property:

CodePen Embed Fallback

Here’s what’s happening in that Pen:

  • animation-delay: Negative delay values force a specific frame (or between) to take effect (positive values don’t work that way). We’ll use this trick to force states.
  • animation-play-state: paused: We’re not actually animating anything, so the animation will stay paused.
  • animation-duration: The actual duration doesn’t matter, it just needs one so there is a time span to hold the different keyframes. We’ll make it a value like 100.001s so that if we delay by 100s, the last keyframe will still work. The duration needs to be longer than the delay value.

The first range input modifies the animation-delay between a range of -100s and 0s.

A real-world use-case

Before we jump straight into the working example, it’s worth discussing this trick in more detail because there’s some nuances you ought to be aware of.

First off, the trick only works with numeric values. So, color values or strings because it’s strictly performing math.

Second, there’s the boolean trick. Consider a variable --value: 10 which can take any numeric value between 0 and 100. We want to apply color if the value is above 5. How do we know if the value is over or below 5? And even if we do know, how does that help actually help us?

--is-above-5: clamp(0, var(--value) - 5, 1) --value--is-above-5Result000 – 5 = -5, clamp() forces a value no less than 0202 – 5 = -3, clamp() forces a value no less than 0505 – 5 = 0717 – 5 = 2, clamp() forces a value no larger than 1

clamp() is like a smarter calc(), in that it allows us to strictly confine a computed value to range while declaring an ideal value. That range is all that is needed to achieve a boolean variable.

Write any math in the second parameter of the clamp() and that will either output 0 (or below) or 1 (or above). Make sure not to write any math that might result in a number between 0 and 1.

Here’s how that works out:

CodePen Embed Fallback

The range input’s only job is to “broadcast” its value by defining a values for --value, --min and --max, then modifying the --value using an oninput event. That is the most minimal thing that can be done get state-like behavior in CSS. No JavaScript needed.

Using CSS math functions, it is possible to infer the “completed” percentage of the progress bar from those same variables:

--completed: calc((var(--value) - var(--min) ) / (var(--max) - var(--min)) * 100);

Now, we know if the value is over a certain percentage, giving us yet another way to make changes by state:

--over-30: clamp(0, var(--completed) - 30, 1); --over-70: clamp(0, var(--completed) - 70, 1); /* ...and so on... */

OK, great, but how can we use this to select a specific keyframe? By using max() function:

--frame: max( calc(1 - var(--over-30)), var(--over-30) * 2, var(--over-70) * 3, var(--is-100) * 4 );

The thing with CSS booleans is that there are many ways to use them to achieve a certain goal, and one must get creative, finding a formula which is short and readable.

In the above formula, the booleans will “toggle” a frame number if the boolean has the value of 1. Since we are using a max function, the the largest toggled frame number will be the computed value of --frame.

Note that the color change has a slight transition. We could have done this with the background: currentColor; on the fill area, which inherits the color from the parent, but I chose to use CSS Houdini to illustrate the power of assigning transitions to CSS variables by declaring its type.

An example of a heavily-used CSS boolean trick can be viewed in the below Pen, which is a CSS-only component with lots of variables that allow a wide range of customization:

CodePen Embed Fallback

I am sure there are many other use cases for this little trick and am excited to see what else might be achieved by the creativity of the community.

The post CSS Switch-Case Conditions appeared first on CSS-Tricks.

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

Use CSS Clamp to create a more flexible wrapper utility

Css Tricks - Wed, 02/17/2021 - 5:54am

I like Andy’s idea here:

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

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

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

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

Direct Link to ArticlePermalink

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

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

Front of the Front / Back of the Front

Css Tricks - Tue, 02/16/2021 - 1:44pm

People really latched onto Brad’s framing. And for good reason. Front-end development has gotten so wide scoping that there are specialists inside of it. Two years ago, I cut it down the middle and now Brad is putting a point on that here, saying he has actual clients who have shifted their hiring strategy away from full-stack and toward these exact distinctions. Nice.

Brad shoots for a simple distinction:

A succinct way I’ve framed the split is that a front-of-the-front-end developer determines the look and feel of a button, while a back-of-the-front-end developer determines what happens when that button is clicked.

Part of me loves the clarity there. And part of me is like But! But! Wait! I’m a front-of-the-front kinda guy, but I totally deal with what happens on click. I’m a state updating machine over here. I’ll fire off that GraphQL mutation myself, thankyouverymuch. I friggin own that onClick.

And yet, I still don’t feel back-of-the-front at all. I can’t set up that GraphQL API or troubleshoot it. I don’t know what the security implications of the network request are. I don’t know if the query I wrote will be performant or not, or where to look at a graph to find out. I think I’d draw the line in a slightly different place than Brad, but he knows that. He’s flexible here:

The line between front-of-the-front-end and back-of-the-front-end can be fuzzy and varies greatly from developer to developer. It’s totally possible that one developer might be able to perform many tasks across the front-end spectrum. But it’s also worth pointing out that’s not super common.

That’s why the term “full-stack” isn’t my favorite. I bet an awful lot of developers have skillsets on both sides of the “great divide” which I think makes it feel like you’re full-stack when it’s more likely you’re cross-stack. Full-stack makes me feel like you’re deeply knowledgeable about literally everything across not only the front-end spectrum, but back-end too. Brad says that’s uncommon and I’ll up that and say it’s downright rare.

My main regret about trying to cut front-end development in half is that it’s too clean of a metaphor for a messy thing.

I live in Bend, Oregon, where outdoor hobbies are like the main thing. You don’t really go up and ask people if they are a summer sports person or a winter sports person because they are almost always both. But one person might be into snowshoeing, downhill skiing, and day hiking, where the next person might be into paddle boarding, nordic skiing, and mountain biking. So, I had this idea of Bend Name Tags where it lists all the outdoor hobbies and you write your name and then circle all the ones that you’re into.

It should almost be like that with front-end development. You write your name and then list out all the things you’re into. Me? I like HTML, CSS, JavaScript, Build Processes, Design, React, WordPress, with a dash of Accessibility, Performance, and Copywriting. What does that make me? Me.

Direct Link to ArticlePermalink

The post Front of the Front / Back of the Front appeared first on CSS-Tricks.

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

Maximally optimizing image loading for the web in 2021

Css Tricks - Tue, 02/16/2021 - 11:16am

Malte Ubl’s list for:

8 image loading optimization techniques to minimize both the bandwidth used for loading images on the web and the CPU usage for image display.

  1. Fluid width images in CSS, not forgetting the height and width attributes in HTML so you get proper aspect-ratio on first render.
  2. Use content-visibility: auto;
  3. Send AVIF when you can.
  4. Use responsive images syntax.
  5. Set far-out expires headers on images and have a cache-busting strategy (like changing the file name).
  6. Use loading="lazy"
  7. Use decoding="async"
  8. Use inline CSS/SVG for a blurry placeholder.

Apparently, there is but one tool that does it all: eleventy-high-performance-blog.

My thoughts:

  • If you are lazy loading, do you really need to do the content-visibilty thing also? They seem very related.
  • Serving AVIF is usually good, but it seems less cut-and-dry than WebP was. You need to make sure your AVIF version is both better and smaller, which feels like a manual process right now. Update: I’m told that AVIF is actually more-reliably smaller (than JPG at least) than WebP is on the whole. I still think it’s worth being careful. This makes me want to outsource format choice to cloud providers that serve in the smallest format they can produce even moreso.
  • The decoding thing seems weird. I’ll totally use it if it’s a free perf win, but if it’s always a good idea, shouldn’t the browser just always do it?
  • I’m not super convinced blurry placeholders are in the same category of necessary as the rest of this stuff. Feels like a trend.

Direct Link to ArticlePermalink

The post Maximally optimizing image loading for the web in 2021 appeared first on CSS-Tricks.

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

The web didn’t change; you did

Css Tricks - Tue, 02/16/2021 - 6:01am

I love this piece from Remy Sharp where he argues that the web didn’t get more complicated over the last 20 years, despite what we might think:

Web development did not change. Web development grew. There are more options now, not different options.

Browsers have become more capable and still work with web pages built over 20 years ago.

[…] The web really didn’t change. It really didn’t become complex. The web development process is not one single path. There is simply more choice and more options.

Remy argues that the web is only really as complex as we make it and, when we choose an enormous framework for a small problem, it’s us that’s choosing the complexity. We really don’t have to build a website with the latest and greatest tools if we’re familiar with the old stuff and there’s no shame in using float over flexbox, if that works for you.

There’s a lot of ego in web design, and there’s a lot of folks out there bashing others for using the “incorrect” tools. But here’s the secret when it comes to making website: there are no perfect tools, and there’s no perfect way to build a website. That sucks, but it’s also exciting because we get to figure it all out; nothing is set in stone.

For example: I use Sass all the time for side projects and I know for a fact that a lotta folks would scoff at that. There’s emotion and Tachyons! There’s plain CSS! There’s PostCSS! But hey: I like Sass for a few things. I like the power it gives me and I like that I’m familiar with it. That doesn’t stop me from reaching for emotion in my day job or experimenting with something new when it comes along.

But old tech isn’t bad just because it’s old. And new tech isn’t good just because it’s new. You can see that sentiment playing out in the comment thread of Chris’ “Front-End Dissatisfaction (and Backing Off)” post.

Direct Link to ArticlePermalink

The post The web didn’t change; you did appeared first on CSS-Tricks.

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

Using AbortController as an Alternative for Removing Event Listeners

Css Tricks - Mon, 02/15/2021 - 11:48am

The idea of an “abortable” fetch came to life in 2017 when AbortController was released. That gives us a way to bail on an API request initiated by fetch() — even multiple calls — whenever we want.

Here’s a super simple example using AbortController to cancel a fetch() request:

const controller = new AbortController(); const res = fetch('/', { signal: controller.signal }); controller.abort(); console.log(res); // => Promise(rejected): "DOMException: The user aborted a request"

You can really see its value when used for a modern interface of setTimeout. This way, making a fetch timeout after, say 10 seconds, is pretty straightforward:

function timeout(duration, signal) { return new Promise((resolve, reject) => { const handle = setTimeout(resolve, duration); signal?.addEventListener('abort', e => { clearTimeout(handle); reject(new Error('aborted')); }); }); } // Usage const controller = new AbortController(); const promise = timeout(10000, controller.signal); controller.abort(); console.log(promise); // => Promise(rejected): "Error: aborted"

But the big news is that addEventListener now accepts an Abort Signal as of Chrome 88. What’s cool about that? It can be used as an alternate of removeEventListener:

const controller = new AbortController(); eventTarget.addEventListener('event-type', handler, { signal: controller.signal }); controller.abort();

What’s even cooler than that? Well, because AbortController is capable of aborting multiple cancelable requests at once, it streamlines the process of removing multiple listeners in one fell swoop. I’ve already found it particularly useful for drag and drop.

Here’s how I would have written a drag and drop script without AbortController, relying two removeEventListener instances to wipe out two different events:

// With removeEventListener el.addEventListener('mousedown', e => { if (e.buttons !== 1) return; const onMousemove = e => { if (e.buttons !== 1) return; /* work */ } const onMouseup = e => { if (e.buttons & 1) return; window.removeEventListener('mousemove', onMousemove); window.removeEventListener('mouseup', onMouseup); } window.addEventListener('mousemove', onMousemove); window.addEventListener('mouseup', onMouseup); // Can’t use `once: true` here because we want to remove the event only when primary button is up });

With the latest update, addEventListener accepts the signal property as its second argument, allowing us to call abort() once to stop all event listeners when they’re no longer needed:

// With AbortController el.addEventListener('mousedown', e => { if (e.buttons !== 1) return; const controller = new AbortController(); window.addEventListener('mousemove', e => { if (e.buttons !== 1) return; /* work */ }, { signal: controller.signal }); window.addEventListener('mouseup', e => { if (e.buttons & 1) return; controller.abort(); }, { signal: controller.signal }); }); CodePen Embed Fallback

Again, Chrome 88 is currently the only place where addEventListener officially accepts an AbortSignal. While other major browsers, including Firefox and Safari, support AbortController, integrating its signal with addEventListener is a no go at the moment… and there are no signals (pun sorta intended) that they plan to work on it. That said, a polyfill is available.

The post Using AbortController as an Alternative for Removing Event Listeners appeared first on CSS-Tricks.

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

Beautiful accessibility with Floating Focus

Css Tricks - Mon, 02/15/2021 - 5:38am

Imagine if your :focus styles animated from element to element as you tab through a site. Like the focus ring up and flew across the page to the next element. The spirit of it is similar to smooth scrolling: it’s easier to understand what is happening when movement accompanies the change¹. Rather than scrolling (or focus change) being an instant jump, movement guides you to the new location.

Guido Bouman thought this would be good for accessibility and looked at some options (e.g. Flying Focus) but ultimately created their own, Floating Focus:

After this exploration we had a good idea of what a good focus state needed. It needs to have a high contrast but not impair readability of the underlying components. It has to guide the user to the next focus target with a form of transition. And it only needs to show for users benefitting from the focus outline.

We’ve covered a similar thing before in 2019 when Maurice Mahan FocusOverlay.

Here’s what I wrote about it back then:

  • It’s a neat effect.
  • I can imagine it being an accessibility win since, while the page will scroll to make sure the next focused element is visible, it doesn’t otherwise help you see where that focus has gone. Movement that directs attention toward the next focused element may help make it more clear.
  • I can imagine it being harmful to accessibility in that it is motion that isn’t usually there and could be surprising and possibly offputting.
  • If it “just works” on all my focusable elements, that’s cool, but I see there are data attributes for controlling the behavior. If I find myself needing to sprinkle behavior control all over my templates to accommodate this specific library, I’d probably be less into it.

In that article, I covered a conditional loading idea for not loading this if prefers-reduced-motion was set to reduce. These days, you might do a conditional ES Modules import.

Don’t take any of this as advice that this movement-based focus stuff is 100% good for accessibility. I don’t feel qualified to make that determination. It is interesting though.

  1. This reminds me of “transitional interfaces” as well. Movement can really help make clear what is happening in a UI.

Direct Link to ArticlePermalink

The post Beautiful accessibility with Floating Focus appeared first on CSS-Tricks.

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

Syndicate content
©2003 - Present Akamai Design & Development.