Tag: shadows”

Scroll Shadows With JavaScript

Scroll shadows are when you can see a little inset shadow on elements if (and only if) you can scroll in that direction. It’s just good UX. You can actually pull it off in CSS, which I think is amazing and one of the great CSS tricks. Except… it just doesn’t work on iOS Safari. It used to work, and then it broke in iOS 13, along with some other useful CSS things, with no explanation why and has never been fixed.

So, now, if you really want scroll shadows (I think they are extra useful on mobile browsers anyway), it’s probably best to reach for JavaScript.

Here’s a pure CSS example so you can see it work in all browsers except iOS Safari. Screenshots:

I’m bringing this up now because I see Jonnie Hallman is blogging about tit again. He mentioned it as an awesome little detail back in May. There are certain interfaces where scroll shadows really extra make sense.

Taking a step back, I thought about the solution that currently worked, using scroll events. If the scroll area has scrolled, show the top and left shadows. If the scroll area isn’t all the way scrolled, show the bottom and right shadows. With this in mind, I tried the simplest, most straight-forward, and least clever approach by putting empty divs at the top, right, bottom, and left of the scroll areas. I called these “edges”, and I observed them using the Intersection Observer API. If any of the edges were not intersecting with the scroll area, I could assume that the edge in question had been scrolled, and I could show the shadow for that edge. Then, once the edge is intersecting, I could assume that the scroll area has reached the edge of the scroll, so I could hide that shadow.

Clever clever. No live demo, unfortunately, but read the post for a few extra details on the implementation.

Other JavaScript-powered examples

I do think if you’re going to do this you should go the IntersectionObserver route though. Would love to see someone port the best of these ideas all together (wink wink).

The post Scroll Shadows With JavaScript appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.


, ,

Designing Beautiful Shadows in CSS

My favorite kind of blog post is when someone takes a subject that I’ve spent all of five minutes considering and then says—no!—this is an enormous topic worthy of a dissertation. Look at all the things you can do with this tiny CSS property!

I was reminded of this when I spotted this post by Josh Comeau about designing beautiful shadows in CSS:

In my humble opinion, the best websites and web applications have a tangible “real” quality to them. There are lots of factors involved to achieve this quality, but shadows are a critical ingredient.

When I look around the web, though, it’s clear that most shadows aren’t as rich as they could be. The web is covered in fuzzy grey boxes that don’t really look much like shadows.

Josh shows the regular old boring shadow approaches and then explores all the ways to improve and optimize them into shadows with real depth. It all comes down to taking a closer look color and exploring the box-shadow CSS property. And speaking of depth, Rob O’Leary’s “Getting Deep Into Shadows” is another comprehensive look at shadows.

I had also completely forgotten about filter: drop-shadow; which is particularly useful on adding shadows to images that you want to throw onto a page. Great stuff all round.

Direct Link to ArticlePermalink

The post Designing Beautiful Shadows in CSS appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.


, ,

Adding Shadows to SVG Icons With CSS and SVG Filters

Why would we need to apply shadows to SVG?

  1. Shadows are a common design feature that can help elements, like icons, stand out. They could be persistent, or applied in different states (e.g. :hover, :focus, or :active) to indicate interaction to users.
  2. Shadows happen in real life, so they can be used on screens to breathe some life into your elements and add a touch of realism to a design.

Since we’re making lists, there are two primary ways we can apply shadows to an SVG:

  1. Using the CSS filter() property
  2. Using an SVG <filter>

Yes, both involve filters! And, yes, both CSS and SVG have their own types of filters. But there is some crossover between these as well. For example, a CSS filter can refer to an SVG <filter>; that is, if we’re working with an inline SVG instead of, say, an SVG used as a background image in CSS.

What you can’t use: the CSS box-shadow property. This is commonly used for shadows, but it follows the rectangular outside edge of elements, not the edges of the SVG elements like we want. Here’s Michelle Barker with a clear explanation:

Two flat kitten faces in bright pink showing ears eyes and whiskers. The first kitten has a drop shadow around its box and the second kitten has a drop shadow around its path edges.

If you’re using an SVG icon font, though, there is always text-shadow. That will indeed work. But let’s focus on those first two as they’re in line with a majority of use cases.

Shadows with CSS filters

The trick to applying a shadow directly to SVG via CSS filters is the drop-shadow() function :

svg {   filter: drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4)); }

That will apply a shadow that starts at 3px horizontally, 5px down, with 2px of blur, and is 40% black. Here are some examples of that:

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.


Chrome Firefox IE Edge Safari
18* 35 No 79 6*

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
91 89 4.4* 6.0-6.1*

Call an SVG filter inside a CSS filter

Say we have an SVG filter in the HTML:

<svg height="0" width="0">      <filter id='shadow' color-interpolation-filters="sRGB">     <feDropShadow dx="2" dy="2" stdDeviation="3" flood-opacity="0.5"/>   </filter>    </svg>

We can use a CSS filter to call that SVG filter by ID instead of values we saw earlier:

svg {   filter: url(#shadow); }

Now that filter is taken from the HTML and referenced in the CSS, which applies it.

Using SVG filter primitives

You might be wondering how we got that SVG <filter> to work. To make a drop shadow with an SVG filter, we make use of a filter primitive. A filter primitive in SVG is an element that takes some sort of image or graphic as an input, then outputs that image or graphic it when it’s called. They sort of work like filters in a graphic editing application, but in code and can only be used inside an SVG <filter> element.

There are lots of different filter primitives in SVG. The one we’re reaching for is <feDropShadow>. I’ll let you guess what to does just by looking at the name.

So, similar to how we had something like this did this with a CSS filter:

svg {   filter: drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4)); }

…we can accomplish the same with the <feDropShadow> SVG filter primitive. There are three key attributes worth calling out as they help define the appearance of the drop shadow:

  • dx — This shifts the position of the shadow along the x-axis.
  • dy — This shifts the position of the shadow along the y-axis.
  • stdDeviation — This defines the standard deviation for the drop shadow’s blur operation. There are other attributes we can use, such as the flood-color for setting the drop shadow color, and flood-opacity for setting the drop shadow’s opacity.

That example includes three <filter> elements, each with their own <feDropShadow> filter primitives.

Using SVG filters

SVG filters are very powerful. We just looked at <feDropShadow>, which is very useful of course, but there is so much more they can do (including Photoshop-like effects) and the subset of stuff we get just for shadows is extensive. Let’s look at some, like colored shadows and inset shadows.

Let’s take the SVG markup for the Twitter logo as an example :

<svg class="svg-icon" viewBox="0 0 20 20">   <path fill="#4691f6" d="M18.258,3.266c-0.693,0.405-1.46,0.698-2.277,0.857c-0.653-0.686-1.586-1.115-2.618-1.115c-1.98,0-3.586,1.581-3.586,3.53c0,0.276,0.031,0.545,0.092,0.805C6.888,7.195,4.245,5.79,2.476,3.654C2.167,4.176,1.99,4.781,1.99,5.429c0,1.224,0.633,2.305,1.596,2.938C2.999,8.349,2.445,8.19,1.961,7.925C1.96,7.94,1.96,7.954,1.96,7.97c0,1.71,1.237,3.138,2.877,3.462c-0.301,0.08-0.617,0.123-0.945,0.123c-0.23,0-0.456-0.021-0.674-0.062c0.456,1.402,1.781,2.422,3.35,2.451c-1.228,0.947-2.773,1.512-4.454,1.512c-0.291,0-0.575-0.016-0.855-0.049c1.588,1,3.473,1.586,5.498,1.586c6.598,0,10.205-5.379,10.205-10.045c0-0.153-0.003-0.305-0.01-0.456c0.7-0.499,1.308-1.12,1.789-1.827c-0.644,0.28-1.334,0.469-2.06,0.555C17.422,4.782,17.99,4.091,18.258,3.266" ></path> </svg>

We’re going to need a <filter> element to do these effects. This needs to be within an <svg> element in the HTML. A <filter> element is never rendered directly in the browser — it is only used as something that can be referenced via the filter attribute in SVG, or the url() function in CSS.

Here is the syntax showing an SVG filter and applying it to a source image :

<svg width="300" height="300" viewBox="0 0 300 300">    <filter id="myfilters">     <!-- All filter effects/primitives go in here -->   </filter>    <g filter="url(#myfilters)">     <!-- Filter applies to everything in this group -->     <path fill="..." d="..." ></path>   </g>  </svg>

The filter element is meant to hold filter primitives as children. It is a container to a series of filter operations that are combined to create a filter effects.

These filter primitive perform a single fundamental graphical operation (e.g. blurring, moving, filling, combining, or distorting) on one or more inputs. They are like building blocks where each SVG filter can be used to in conjunction with others to create an effect. <feGaussianBlur> is a popular filter primitive used to add a blur effect.

Let’s say we define the following SVG filter with <feGaussianBlur>:

<svg version="1.1" width="0" height="0">   <filter id="gaussian-blur">     <feGaussianBlur stdDeviation="1 0" />   </filter> </svg>

When applied on an element, this filter creates a Gaussian blur that blurs the element on a 1px radius on the x-axis, but no blurring on the y-axis. Here’s the result, with and without the effect:

It is possible to use multiple primitives inside a single filter. This will create interesting effects, however, you need to make the different primitives aware of each other. Bence Szabó has a crazy cool set of patterns he created this way.

When combining multiple filter primitives, the first primitive uses the original graphic (SourceGraphic) as its graphic input. Any subsequent primitive uses the result of the filter effect before it as its input. And so on. But we can get some flexibility on that with using the in, in2 and result attributes on primitive elements. Steven Bradley has an excellent write-up on filter primitives that dates back to 2016, but still hold true today.

There are 17 primitives we can use today:

  • <feGaussianBlur>
  • <feDropShadow>
  • <feMorphology>
  • <feDisplacementMap>
  • <feBlend>
  • <feColorMatrix>
  • <feConvolveMatrix>
  • <feComponentTransfer>
  • <feSpecularLighting>
  • <feDiffuseLighting>
  • <feFlood>
  • <feTurbulence>
  • <feImage>
  • <feTile>
  • <feOffset>
  • <feComposite>
  • <feMerge>

Notice the fe prefix on all of them. That stands for filter effect. Understanding SVG filters is challenging. An effect like an inset shadow requires a verbose syntax that is difficult to grasp without a thorough understanding of math and color theory. (Rob O’Leary’s “Getting Deep Into Shadows” is a good place to start.)

Rather than running down the rabbit hole of all that, we’re going to work with some pre-made filters. Fortunately, there are a lot of ready-to-use SVG filters around.

Inset shadows

To use filter effect on the Twitter logo, we need to declare it in our “SVG source document” with a unique ID for referencing in our <filter> tag.

<filter id='inset-shadow'>   <!-- Shadow offset -->   <feOffset     dx='0'     dy='0'   />    <!-- Shadow blur -->   <feGaussianBlur     stdDeviation='1'     result='offset-blur'   />    <!-- Invert drop shadow to make an inset shadow -->   <feComposite     operator='out'     in='SourceGraphic'     in2='offset-blur'     result='inverse'   />      <!-- Cut color inside shadow -->   <feFlood     flood-color='black'     flood-opacity='.95'     result='color'   />   <feComposite     operator='in'     in='color'     in2='inverse'     result='shadow'   />    <!-- Placing shadow over element -->   <feComposite     operator='over'     in='shadow'     in2='SourceGraphic'   /> </filter>

There are four different primitives in there and each one performs a different function. But, taken together, they achieving an inset shadow.

Now that we’ve created this inset shadow filter, we can apply it to our SVG. We’ve already seen how to apply it via CSS. Something like:

.filtered {   filter: url(#myfilters); }  /* Or apply only in certain states, like: */ svg:hover, svg:focus {   filter: url(#myfilters); } 

We can also apply an SVG <filter> directly within the SVG syntax with the filter attribute. That’s like:

<svg>    <!-- Apply a single filter -->   <path d="..." filter="url(#myfilters)" />    <!-- Or apply to a whole group of elements -->   <g filter="url(#myfilters)">     <path d="..." />     <path d="..." />   </g> </svg>

More examples

Here are some more shadow examples from Oleg Solomka:

Note that the basic shadows here are probably a bit more complicated than they need to be. For example, a colored shadow can still be done with <feDropShadow> like:

<feDropShadow dx="-0.8" dy="-0.8" stdDeviation="0"   flood-color="pink" flood-opacity="0.5"/>

But that embossed effect is pretty great as a filter!

Also note that you might see SVG filters in SVG syntax like this:

<svg height="0" width="0" style="position: absolute; margin-left: -100%;">   <defs>     <filter id="my-filters">       <!-- ... -->     </filter>      <symbol id="my-icon">       <!-- ... -->     </symbol>   </defs> </svg>

On the first line there, that’s saying: this SVG shouldn’t render at all — it’s just stuff that we intend to use later. The <defs> tag says something similar: we’re just defining these things to use later. That way, we don’t have to repeat ourselves by writing things out over and again. We’ll reference the filter by ID, and the symbols as well, perhaps like:

<svg>   <use xlink:href="#my-icon" /> </svg>

SVG filters have wide support (even in Internet Explorer and Edge!) with very fast performance.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.


Chrome Firefox IE Edge Safari
8 3 10 12 6

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
91 89 4.4 6.0-6.1

Wrapping things up

A final comparison:

  • CSS filters are easier to use, but are much more limited. I don’t think it’s possible to add an inset shadow with the drop-shadow() function, for example.
  • SVG filters are much more robust, but much more complicated as well, and require having the <filter> somewhere in the HTML.
  • They both have great browser support and perform well on all modern browsers, though SVG filters have (surprisingly) the deepest browser support.

In this article, we have seen why and how to apply shadow to SVG icons with examples on each. Have you done this, but did it a different way than anything we looked at? Have you tried to do a shadow effect that you found impossible to pull off? Please share!

The post Adding Shadows to SVG Icons With CSS and SVG Filters appeared first on CSS-Tricks.

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


, , ,

Creating Colorful, Smart Shadows

A bona fide CSS trick from Kirupa Chinnathambi here. To match a colored shadow with the colors in the background-image of an element, you inherit the background in a pseudo-element, kick it behind the original, then blur and filter it.

.colorfulShadow {   position: relative; }  .colorfulShadow::after {   content: "";   width: 100%;   height: 100%;   position: absolute;   background: inherit;   background-position: center center;   filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.50)) blur(20px);   z-index: -1; }

Negative z-index is always a yellow flag for me as that only works if there are no intermediary backgrounds. But the trick holds. There would always be some other way to layer the backgrounds (like a <span> or whatever).

For some reason this made me think of a demo I saw (I can’t remember who to credit!). Emojis had text-shadow on them, which really made them pop. And those shadows could also be colorized to a similar effect.

Direct Link to ArticlePermalink

The post Creating Colorful, Smart Shadows appeared first on CSS-Tricks.

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


, , ,

Getting Deep into Shadows

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.

A view of a BMX biker from above leaping over a vast area of light brown land with the words free ride along the bottom edge in large, bold, and white block lettering.
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.

Screenshot of a webpage with a light pink background with a white box that contains the site content with a headline that reads "Ride as Much or as Little" in red, an email subscription form, and a large image of a red and white bicycle to the right.
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.

A masonry grid of photos on a mobile screen. The purple header that contains the page title and hamburger menu has a shadow along its bottom edge that separates it from the white background of the photos.

White modal with a list of checkboxes. The modal has an underlying black shadow against the background.

A two-by-three grid of cards on a mobile screen. Each card has a light shallow shadow against a white background.

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.

Screenshot of Apple's Reminders app on a desktop. The left column that contains search and navigation is opaque and blends lightly into the desktop background while the solid white right column contains a checkbox list of reminders.

Screenshot of Apple's Maps app. The left column contains the map addresses and different route options with an opaque background that lightly blends in with the desktop background. The right column contains the map and does not blend in with the background.

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.

Photo of an orange with light shining on it from the top right. That area is brighter than the left side which is covered in shadow. The ground contains a light reflection of the orange.

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.

Illustration showing the effects of Hue, Tint, Tone, and Shade on red rectangles. Each rectangle is a slightly different shade of red where tint adds white, tone adds gray and shade adds black.

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.

Two vertically stacked illustrations.The top is a green circle with a yellow light source coming at it from the left and both umbra and penumbra shadows are cast to the right. The bottom illustration is the same green circle and light source, but with a solid black shadow cast to the right.

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.

This stuff comes up in just about everything we do, even when writing with a pencil.

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!

Showing two browser mockups side by side. The left has light shining on it from all four directions showing uniform light and no shadows. The right has a single light source from the top casting a shadow along the bottom edge.

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.


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.

Showing a mobile screen flat on a light blue background with header, box, and navigational elements elevated over the screen showing depth.
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.

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

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.

Interesting effects is another.

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

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.

Two vertically stacked examples showing a white circle with a yellow and a grey circle behind it and the CSS code snippets that create the effect. On the top, the gray shadow is above the yellow shadow. On the bottom, the yellow shadow is above the gray shadow.

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.

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.

Showing two of the same card component side-by-side. They are brightly colored with a background gradient that goes from red to gold. The Nike logo is at the top, a title is below it, then a paragraph of white text beneath that. A red show with an exaggerated shadow is on both cards. The cards illustrated the difference between box shadow, which follows the boundaries of the card's edges, and drop shadow, which includes the shape of the shoe outside the card boundary.

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.

The same goes for text shadows.

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:

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.

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.

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.

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.

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.


, , ,

Simulating Drop Shadows with the CSS Paint API

Ask a hundred front-end developers, and most, if not all, of them will have used the box-shadow property in their careers. Shadows are enduringly popular, and can add an elegant, subtle effect if used properly. But shadows occupy a strange place in the CSS box model. They have no effect on an element’s width and height, and are readily clipped if overflow on a parent (or grandparent) element is hidden.

We can work around this with standard CSS in a few different ways. But, now that some of the CSS Houdini specifications are being implemented in browsers, there are tantalizing new options. The CSS Paint API, for example, allows developers to generate images programmatically at run time. Let’s look at how we can use this to paint a complex shadow within a border image.

A quick primer on Houdini

You may have heard of some newfangled CSS tech hitting the platform with the catchy name of Houdini. Houdini promises to deliver greater access to how the browser paints the page. As MDN states, it is “a set of low-level APIs that exposes parts of the CSS engine, giving developers the power to extend CSS by hooking into the styling and layout process of a browser’s rendering engine.”

The CSS Paint API

The CSS Paint API is one of the first of these APIs to hit browsers. It is a W3C candidate recommendation. This is the stage when specifications start to see implementation. It is currently available for general use in Chrome and Edge, while Safari has it behind a flag and Firefox lists it as “worth prototyping”. There is a polyfill available for unsupported browsers, though it will not run in IE11.

While the CSS Paint API is enabled in Chromium, passing arguments to the paint() function is still behind a flag. You’ll need to enable experimental web platform features for the time being. These examples may not, unfortunately, work in your browser of choice at the moment. Consider them an example of things to come, and not yet ready for production.

The approach

We’re going to generate an image with a shadow, and then use it for a border-image… huh? Well, let’s take a deeper look.

As mentioned above, shadows don’t add any width or height to an element, but spread out from its bounding box. In most cases, this isn’t a problem, but those shadows are vulnerable to clipping. A common workaround is to create some sort of offset with either padding or margin.

What we’re going to do is build the shadow right into the element by painting it in to the border-image area. This has a few key advantages:

  1. border-width adds to the overall element width
  2. Content won’t spill into the border area and overlap the shadow
  3. Padding won’t need any extra width to accommodate the shadow and content
  4. Margins around the element won’t interfere with that element’s siblings

For that aforementioned group of one hundred developers who’ve used box-shadow, it’s likely only a few of them have used border-image. It’s a funky property. Essentially, it takes an image and slices it into nine pieces, then places them in the four corners, sides and (optionally) the center. You can read more about how all this works in Nora Brown’s article.

The CSS Paint API will handle the heavy lifting of generating the image. We’re going to create a module for it that tells it how to layer a series of shadows on top of each other. That image will then get used by border-image.

These are the steps we’ll take:

  1. Set up the HTML and CSS for the element we want to paint in
  2. Create a module that draws the image
  3. Load the module into a paint worklet
  4. Call the worklet in CSS with the new paint() function

Setting up the canvas

You’re going to hear the term canvas a few times here, and in other CSS Paint API resources. If that term sounds familiar, you’re right. The API works in a similar way to the HTML <canvas> element.

First, we have to set up the canvas on which the API will paint. This area will have the same dimensions as the element that calls the paint function. Let’s make a 300×300 div.

<section>   <div class="foo"></div> </section>

And the styles:

.foo {   border: 15px solid #efefef;   box-sizing: border-box;   height: 300px;   width: 300px; }

Creating the paint class

HTTPS is required for any JavaScript worklet, including paint worklets. You won’t be able to use it at all if you’re serving your content over HTTP.

The second step is to create the module that is loaded into the worklet — a simple file with the registerPaint() function. This function takes two arguments: the name of the worklet and a class that has the painting logic. To stay tidy, we’ll use an anonymous class.

registerPaint(   "shadow",   class {} );

In our case, the class needs two attributes, inputProperties and inputArguments, and a method, paint().

registerPaint(   "shadow",   class {     static get inputProperties() {       return [];     }     static get inputArguments() {       return [];     }     paint(context, size, props, args) {}   } );

inputProperties and inputArguments are optional, but necessary to pass data into the class.

Adding input properties

We need to tell the worklet which CSS properties to pull from the target element with inputProperties. It’s a getter that returns an array of strings.

In this array, we list both the custom and standard properties the class needs: --shadow-colors, background-color, and border-top-width. Pay particular attention to how we use non-shorthand properties.

static get inputProperties() {   return ["--shadow-colors", "background-color", "border-top-width"]; }

For simplicity, we’re assuming here that the border is even on all sides.

Adding arguments

Currently, inputArguments are still behind a flag, hence enabling experimental features. Without them, use inputProperties and custom properties instead.

We also pass arguments to the paint module with inputArguments. At first glance, they may seem superfluous to inputProperties, but there are subtle differences in how the two are used.

When the paint function is called in the stylesheet, inputArguments are explicitly passed in the paint() call. This gives them an advantage over inputProperties, which might be listening for properties that could be modified by other scripts or styles. For example, if you’re using a custom property set on :root that changes, it may filter down and affect the output.

The second important difference for inputArguments, which is not intuitive, is that they are not named. Instead, they are referenced as items in an array within the paint method. When we tell inputArguments what it’s receiving, we are actually giving it the type of the argument.

The shadow class is going to need three arguments: one for X positions, one for Y positions, and one for blurs. We’ll set that up as three space-separated lists of integers.

Anyone who has registered a custom property may recognize the syntax. In our case, the <integer> keyword means any whole number, while + denotes a space-separated list.

static get inputArguments() {   return ["<integer>+", "<integer>+", "<integer>+"]; }

To use inputProperties in place of inputArguments, you could set custom properties directly on the element and listen for them. Namespacing would be critical to ensure inherited custom properties from elsewhere don’t leak in.

Adding the paint method

Now that we have the inputs, it’s time to set up the paint method.

A key concept for paint() is the context object. It is similar to, and works much like, the HTML <canvas> element context, albeit with a few small differences. Currently, you cannot read pixels back from the canvas (for security reasons), or render text (there’s a brief explanation why in this GitHub thread).

The paint() method has four implicit parameters:

  1. The context object
  2. Geometry (an object with width and height)
  3. Properties (a map from inputProperties)
  4. Arguments (the arguments passed from the stylesheet)
paint(ctx, geom, props, args) {}

Getting the dimensions

The geometry object knows how big the element is, but we need to adjust for the 30 pixels of total border on the X and Y axis:

const width = (geom.width - borderWidth * 2); const height = (geom.height - borderWidth * 2);

Using properties and arguments

Properties and arguments hold the resolved data from inputProperties and inputArguments. Properties come in as a map-like object, and we can pull values out with get() and getAll():

const borderWidth = props.get("border-top-width").value; const shadowColors = props.getAll("--shadow-colors");

get() returns a single value, while getAll() returns an array.

--shadow-colors will be a space-separated list of colors which can be pulled into an array. We’ll register this with the browser later so it knows what to expect.

We also need to specify what color to fill the rectangle with. It will use the same background color as the element:

ctx.fillStyle = props.get("background-color").toString();

As mentioned earlier, arguments come into the module as an array, and we reference them by index. They’re of the type CSSStyleValue right now — let’s make it easier to iterate through them:

  1. Convert the CSSStyleValue into a string with its toString() method
  2. Split the result on spaces with a regex
const blurArray = args[2].toString().split(/s+/); const xArray = args[0].toString().split(/s+/); const yArray = args[1].toString().split(/s+/); // e.g. ‘1 2 3’ -> [‘1’, ‘2’, ‘3’]

Drawing the shadows

Now that we have the dimensions and properties, it’s time to draw something! Since we need a shadow for each item in shadowColors, we’ll loop through them. Start with a forEach() loop:

shadowColors.forEach((shadowColor, index) => {  });

With the index of the array, we’ll grab the matching values from the X, Y, and blur arguments:

shadowColors.forEach((shadowColor, index) => {   ctx.shadowOffsetX = xArray[index];   ctx.shadowOffsetY = yArray[index];   ctx.shadowBlur = blurArray[index];   ctx.shadowColor = shadowColor.toString(); });

Finally, we’ll use the fillRect() method to draw in the canvas. It takes four arguments: X position, Y position, width, and height. For the position values, we’ll use border-width from inputProperties; this way, the border-image is clipped to contain just the shadow around the rectangle.

shadowColors.forEach((shadowColor, index) => {   ctx.shadowOffsetX = xArray[index];   ctx.shadowOffsetY = yArray[index];   ctx.shadowBlur = blurArray[index];   ctx.shadowColor = shadowColor.toString();    ctx.fillRect(borderWidth, borderWidth, width, height); });

This technique can also be done using a canvas drop-shadow filter and a single rectangle. It’s supported in Chrome, Edge, and Firefox, but not Safari. See a finished example on CodePen.

Almost there! There are just a few more steps to wire things up.

Registering the paint module

We first need to register our module as a paint worklet with the browser. This is done back in our main JavaScript file:

CSS.paintWorklet.addModule("https://codepen.io/steve_fulghum/pen/bGevbzm.js"); https://codepen.io/steve_fulghum/pen/BazexJX

Registering custom properties

Something else we should do, but isn’t strictly necessary, is to tell the browser a little more about our custom properties by registering them.

Registering properties gives them a type. We want the browser to know that --shadow-colors is a list of actual colors, not just a string.

If you need to target browsers that don’t support the Properties and Values API, don’t despair! Custom properties can still be read by the paint module, even if not registered. However, they will be treated as unparsed values, which are effectively strings. You’ll need to add your own parsing logic.

Like addModule(), this is added to the main JavaScript file:

CSS.registerProperty({   name: "--shadow-colors",   syntax: "<color>+",   initialValue: "black",   inherits: false });

You can also use @property in your stylesheet to register properties. You can read a brief explanation on MDN.

Applying this to border-image

Our worklet is now registered with the browser, and we can call the paint method in our main CSS file to take the place of an image URL:

border-image-source: paint(shadow, 0 0 0, 8 2 1, 8 5 3) 15; border-image-slice: 15;

These are unitless values. Since we’re drawing a 1:1 image, they equate to pixels.

Adapting to display ratios

We’re almost done, but there’s one more problem to tackle.

For some of you, things might not look quite as expected. I’ll bet you sprung for the fancy, high DPI monitor, didn’t you? We’ve encountered an issue with the device pixel ratio. The dimensions that have been passed to the paint worklet haven’t been scaled to match.

Rather than go through and scale each value manually, a simple solution is to multiply the border-image-slice value. Here’s how to do it for proper cross-environment display.

First, let’s register a new custom property for CSS that exposes window.devicePixelRatio:

CSS.registerProperty({   name: "--device-pixel-ratio",   syntax: "<number>",   initialValue: window.devicePixelRatio,   inherits: true });

Since we’re registering the property, and giving it an initial value, we don’t need to set it on :root because inherit: true passes it down to all elements.

And, last, we’ll multiply our value for border-image-slice with calc():

.foo {   border-image-slice: calc(15 * var(--device-pixel-ratio)); }

It’s important to note that paint worklets also have access to the devicePixelRatio value by default. You can simply reference it in the class, e.g. console.log(devicePixelRatio).


Whew! We should now have a properly scaled image being painted in the confines of the border area!

Live demo (best viewed in Chrome and Edge)
Live demo (best viewed in Chrome and Edge)

Bonus: Apply this to a background image

I’d be remiss to not also demonstrate a solution that uses background-image instead of border-image. It’s easy to do with just a few modifications to the module we just wrote.

Since there isn’t a border-width value to use, we’ll make that a custom property:

CSS.registerProperty({   name: "--shadow-area-width",   syntax: "<integer>",   initialValue: "0",   inherits: false });

We’ll also have to control the background color with a custom property as well. Since we’re drawing inside the content box, setting an actual background-color will still show behind the background image.

CSS.registerProperty({   name: "--shadow-rectangle-fill",   syntax: "<color>",   initialValue: "#fff",   inherits: false });

Then set them on .foo:

.foo {   --shadow-area-width: 15;   --shadow-rectangle-fill: #efefef; }

This time around, paint() gets set on background-image, using the same arguments as we did for border-image:

.foo {   --shadow-area-width: 15;   --shadow-rectangle-fill: #efefef;   background-image: paint(shadow, 0 0 0, 8 2 1, 8 5 3); }

As expected, this will paint the shadow in the background. However, since background images extend into the padding box, we’ll need to adjust padding so that text doesn’t overlap:

.foo {   --shadow-area-width: 15;   --shadow-rectangle-fill: #efefef;   background-image: paint(shadow, 0 0 0, 8 2 1, 8 5 3);   padding: 15px; }


As we all know, we don’t live in a world where everyone uses the same browser, or has access to the latest and greatest. To make sure they don’t receive a busted layout, let’s consider some fallbacks.

Padding fix

Padding on the parent element will condense the content box to accommodate for shadows that extend from its children.

section.parent {   padding: 6px; /* size of shadow on child */ }

Margin fix

Margins on child elements can be used for spacing, to keep shadows away from their clipping parents:

div.child {   margin: 6px; /* size of shadow on self */ }

Combining border-image with a radial gradient

This is a little more off the beaten path than padding or margins, but it’s got great browser support. CSS allows gradients to be used in place of images, so we can use one within a border-image, just like how we did with paint(). This may be a great option as a fallback for the Paint API solution, as long as the design doesn’t require exactly the same shadow:

Gradients can be finicky and tricky to get right, but Geoff Graham has a great article on using them.

div {   border: 6px solid;   border-image: radial-gradient(     white,     #aaa 0%,     #fff 80%,     transparent 100%   )   25%; }

An offset pseudo-element

If you don’t mind some extra markup and CSS positioning, and need an exact shadow, you can also use an inset pseudo-element. Beware the z-index! Depending on the context, it may need to be adjusted.

.foo {   box-sizing: border-box;   position: relative;   width: 300px;   height: 300px;   padding: 15px; }  .foo::before {   background: #fff;   bottom: 15px;   box-shadow: 0px 2px 8px 2px #333;   content: "";   display: block;   left: 15px;   position: absolute;   right: 15px;   top: 15px;   z-index: -1; }

Final thoughts

And that, folks, is how you can use the CSS Paint API to paint just the image you need. Is it the first thing to reach for in your next project? Well, that’s for you to decide. Browser support is still forthcoming, but pushing forward.

In all fairness, it may add far more complexity than a simple problem calls for. However, if you’ve got a situation that calls for pixels put right where you want them, the CSS Paint API is a powerful tool to have.

What’s most exciting though, is the opportunity it provides for designers and developers. Drawing shadows is only a small example of what the API can do. With some imagination and ingenuity, all sorts of new designs and interactions are possible.

Further reading

The post Simulating Drop Shadows with the CSS Paint API appeared first on CSS-Tricks.

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


, , ,

Creating Playful Effects With CSS Text Shadows

Let’s have a look at how we can use the CSS text-shadow property to create truly 3D-looking text. You might think of text-shadow as being able to apply blurred, gradient-looking color behind text, and you would be right! But just like box-shadow, you can control how blurred the shadow is, including taking it all the way down to no blur at all. That, combined with comma-separating shadows and stacking them, is the CSS trickery we’ll be doing here.

By the end, we’ll have something that looks like this:

Quick refresher on text-shadow

The syntax is like this:

.el {   text-shadow: [x-offset] [y-offset] [blur] [color]; }
  • x-offset: Position on the x-axis. A positive value moves the shadow to the right, a negative value moves the shadow to the left. (required)
  • y-offset: Position on the y-axis. A positive value moves the shadow to the bottom, a negative value moves the shadow to the top. (required)
  • blur: How much blur the shadow should have. The higher the value, the softer the shadow. The default value is 0px (no blur). (optional)
  • color: The color of the shadow. (required)

The first shadow

Let’s start creating our effect by adding just one shadow. The shadow will be pushed 6px to the right and 6px to the bottom:

:root {   --text: #5362F6; /* Blue */   --shadow: #E485F8; /* Pink */ } 
 .playful {   color: var(--text);   text-shadow: 6px 6px var(--shadow); }

Creating depth with more shadows

All we have is a flat shadow at this point — there’s not much 3D to it yet. We can create the depth and connect the shadow to the actual text by adding more text-shadow instances to the same element. All it takes is comma-separating them. Let’s start with adding one more in the middle:

.playful {   color: var(--text);   text-shadow: 6px 6px var(--shadow),                3px 3px var(--shadow); }

This is already getting somewhere, but we’ll need to add a few more shadows for it to look good. The more steps we add, the more detailed the the end result will be. In this example, we’ll start from 6px 6px and gradually build down in 0.25px increments until we’ve reached 0.

.playful {   color: var(--text);   text-shadow:      6px 6px        var(--shadow),      5.75px 5.75px  var(--shadow),      5.5px 5.5px    var(--shadow),      5.25px 5.25px  var(--shadow),     5px 5px        var(--shadow),      4.75px 4.75px  var(--shadow),      4.5px 4.5px    var(--shadow),      4.25px 4.25px  var(--shadow),     4px 4px        var(--shadow),     3.75px 3.75px  var(--shadow),     3.5px 3.5px    var(--shadow),     3.25px 3.25px  var(--shadow),     3px 3px        var(--shadow),     2.75px 2.75px  var(--shadow),     2.5px 2.5px    var(--shadow),     2.25px 2.25px  var(--shadow),     2px 2px        var(--shadow),     1.75px 1.75px  var(--shadow),     1.5px 1.5px    var(--shadow),     1.25px 1.25px  var(--shadow),     1px 1px        var(--shadow),     0.75px 0.75px  var(--shadow),     0.5px 0.5px    var(--shadow),     0.25px 0.25px  var(--shadow); }

Simplifying the code with Sass

The result may look good, but the code right now is quite hard to read and edit. If we want to make the shadow larger, we’d have to do a lot of copying and pasting to achieve it. For example, increasing the shadow size to 10px would mean adding 16 more shadows manually.

And that’s where SCSS comes in the picture. We can use functions to automate generating all of the shadows.

@function textShadow($ precision, $ size, $ color){   $ value: null;    $ offset: 0;   $ length: $ size * (1 / $ precision) - 1; 
   @for $ i from 0 through $ length {     $ offset: $ offset + $ precision;     $ shadow: $ offset + px $ offset + px $ color;     $ value: append($ value, $ shadow, comma);   } 
   @return $ value; } 
 .playful {   color: #5362F6;   text-shadow: textShadow(0.25, 6, #E485F8); }

The function textShadow takes three different arguments: the precision, size and color of the shadow. It then creates a loop where the offset gets increased by $ precision (in this case, it’s 0.25px) until it reaches the total size (in this case 6px) of the shadow.

This way we can easily increase the size or precision of the shadow. For example, to create a shadow that’s 10px large and increases with 0.1px, we would only have to change this in our code:

text-shadow: textShadow(0.1, 10, #E485F8);

Alternating colors

We want to spice things up a bit by going for alternating colors. We will split up the text in individual letters wrapped in spans (this can be done manually, or automated with React or JavaScript). The output will look like this:

<p class="playful" aria-label="Wash your hands!">   <span aria-hidden="true">W</span><span aria-hidden="true">a</span><span aria-hidden="true">s</span><span aria-hidden="true">h</span> ... </p>

Then we can use the :nth-child() selector on the spans to change the color of their text and shadow.

.playful span:nth-child(2n) {   color: #ED625C;   text-shadow: textShadow(0.25, 6, #F2A063); }

If we had done this in vanilla CSS, then here’s what we’d end up with:

.playful span {   color: var(--text);   text-shadow:      6px 6px var(--shadow),     5.75px 5.75px var(--shadow),     5.5px 5.5px var(--shadow),     5.25px 5.25px var(--shadow),     5px 5px var(--shadow),     4.75px 4.75px var(--shadow),     4.5px 4.5px var(--shadow),     4.25px 4.25px var(--shadow),     4px 4px var(--shadow),     3.75px 3.75px var(--shadow),     3.5px 3.5px var(--shadow),     3.25px 3.25px var(--shadow),     3px 3px var(--shadow),'     2.75px 2.75px var(--shadow),     2.5px 2.5px var(--shadow),     2.25px 2.25px var(--shadow),     2px 2px var(--shadow),     1.75px 1.75px var(--shadow),     1.5px 1.5px var(--shadow),     1.25px 1.25px var(--shadow),     1px 1px var(--shadow),     0.75px 0.75px var(--shadow),     0.5px 0.5px var(--shadow),     0.25px 0.25px var(--shadow); } 
 .playful span:nth-child(2n) {   --text: #ED625C;   --shadow: #F2A063; }

We can repeat the same a couple of times with other colors and indexes until we achieve a pattern we like:

Bonus points: Adding animation

Using the same principles, we can bring the text to life even more by adding animations. First, we’ll add a repeating animation that makes each span move up and down:

.playful span {   color: #5362F6;   text-shadow: textShadow(0.25, 6, #E485F8);   position: relative;   animation: scatter 1.75s infinite; }

We can optimize this a little further by using the prefers-reduced-motion media query. That way, folks who don’t want the animation won’t get it.

.playful span {   color: #5362F6;   text-shadow: textShadow(0.25, 6, #E485F8);   position: relative;   animation: scatter 1.75s infinite; }  @media screen and (prefers-reduced-motion: reduce) {   animation: none; }

Then, in each nth-child(n) we’ll add a different animation delay.

.playful span:nth-child(2n) {   color: #ED625C;   text-shadow: textShadow(0.25, 6, #F2A063);   animation-delay: 0.3s; }

The post Creating Playful Effects With CSS Text Shadows appeared first on CSS-Tricks.


, , , ,

Using “box shadows” and clip-path together

Let’s do a little step-by-step of a situation where you can’t quite do what seems to make sense, but you can still get it done with CSS trickery. In this case, it’ll be applying a shadow to a shape.

You make a box

.tag {   background: #FB8C00;   color: #222;   font: bold 32px system-ui;   padding: 2rem 3rem 2rem 4rem; }

You fashion it into a nice tag shape

You use clip-path because it’s great for that.

.tag {   /* ... */   clip-path: polygon(30px 0%, 100% 0%, 100% 100%, 30px 100%, 0 50%) }

You want a shadow on it, so you…

Try to use box-shadow.

.tag {   /* ... */   box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5); }

But it doesn’t work. Nothing shows up. You think you’re going crazy. You assume you have the syntax wrong. You don’t. The problem is that clip-path is cutting it off.

You can drop-shadow a parent element instead

There is a filter that does shadows as well: drop-shadow(). But you can’t use it directly on the element because the clip-path will cut it off as well. So you make a parent:

<span class="tag-wrap">   <span class="tag">     Tag   </span> </span>

You can’t use box-shadow on that parent either, because the parent is still a rectangle and the shadow will look wrong. But you can use filter, and the shadow will follow the shape.

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

That’s all.

The post Using “box shadows” and clip-path together appeared first on CSS-Tricks.


, , , ,