搜尋
首頁web前端css教學使用CSS和SVG過濾器向SVG圖標添加陰影

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

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 ; 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:

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.

Desktop

Mobile / Tablet

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"></fedropshadow>
  </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 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 element.

There are lots of different filter primitives in SVG. The one we’re reaching for is . 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 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 elements, each with their own filter primitives.

Using SVG filters

SVG filters are very powerful. We just looked at , 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 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 element to do these effects. This needs to be within an element in the HTML. A 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>
    <!-- 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. is a popular filter primitive used to add a blur effect.

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

<svg version="1.1" width="0" height="0">
  <filter>
    <fegaussianblur stddeviation="1 0"></fegaussianblur>
  </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:

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

<filter id="inset-shadow">
  <!-- Shadow offset -->
  <feoffset dx="0" dy="0"></feoffset>

  <!-- Shadow blur -->
  <fegaussianblur stddeviation="1" result="offset-blur"></fegaussianblur>

  <!-- Invert drop shadow to make an inset shadow -->
  <fecomposite operator="out" in="SourceGraphic" in2="offset-blur" result="inverse"></fecomposite>
  
  <!-- Cut color inside shadow -->
  <feflood flood-color="black" flood-opacity=".95" result="color"></feflood>
  <fecomposite operator="in" in="color" in2="inverse" result="shadow"></fecomposite>

  <!-- Placing shadow over element -->
  <fecomposite operator="over" in="shadow" in2="SourceGraphic"></fecomposite>
</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 directly within the SVG syntax with the filter attribute. That’s like:

<svg>

  <!-- Apply a single filter -->
  <path d="..." filter="url(#myfilters)"></path>

  <!-- Or apply to a whole group of elements -->
  <g filter="url(#myfilters)">
    <path d="..."></path>
    <path d="..."></path>
  </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 like:

<fedropshadow dx="-0.8" dy="-0.8" stddeviation="0" flood-color="pink" flood-opacity="0.5"></fedropshadow>

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>
      <!-- ... -->
    </filter>

    <symbol>
      <!-- ... -->
    </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 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"></use>
</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.

Desktop

Mobile / Tablet

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

以上是使用CSS和SVG過濾器向SVG圖標添加陰影的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
丟失的CSS技巧cohost.org丟失的CSS技巧cohost.orgApr 25, 2025 am 09:51 AM

在這篇文章中,布萊克·莫里(Blackle Mori)向您展示了一些駭客,同時試圖推動同位HTML支持的極限。如果您敢於使用這些,以免您也被標記為CSS罪犯。

光標的下一個CSS樣式光標的下一個CSS樣式Apr 23, 2025 am 11:04 AM

具有CSS的自定義光標很棒,但是我們可以將JavaScript提升到一個新的水平。使用JavaScript,我們可以在光標狀態之間過渡,將動態文本放置在光標中,應用複雜的動畫並應用過濾器。

世界碰撞:使用樣式查詢的鑰匙幀碰撞檢測世界碰撞:使用樣式查詢的鑰匙幀碰撞檢測Apr 23, 2025 am 10:42 AM

互動CSS動畫和元素相互啟動的元素在2025年似乎更合理。雖然不需要在CSS中實施乒乓球,但CSS的靈活性和力量的增加,可以懷疑Lee&Aver Lee有一天會成為一種

使用CSS背景過濾器進行UI效果使用CSS背景過濾器進行UI效果Apr 23, 2025 am 10:20 AM

有關利用CSS背景濾波器屬性來樣式用戶界面的提示和技巧。您將學習如何在多個元素之間進行背景過濾器,並將它們與其他CSS圖形效果集成在一起以創建精心設計的設計。

微笑嗎?微笑嗎?Apr 23, 2025 am 09:57 AM

好吧,事實證明,SVG的內置動畫功能從未按計劃進行棄用。當然,CSS和JavaScript具有承載負載的能力,但是很高興知道Smil並沒有像以前那樣死在水中

'漂亮”在情人眼中'漂亮”在情人眼中Apr 23, 2025 am 09:40 AM

是的,讓#039;跳上文字包裝:Safari Technology Preview In Pretty Landing!但是請注意,它與在鉻瀏覽器中的工作方式不同。

CSS-tricks編年史XLIIICSS-tricks編年史XLIIIApr 23, 2025 am 09:35 AM

此CSS-tricks更新了,重點介紹了年鑑,最近的播客出現,新的CSS計數器指南以及增加了幾位新作者,這些新作者貢獻了有價值的內容。

tailwind的@Apply功能比聽起來更好tailwind的@Apply功能比聽起來更好Apr 23, 2025 am 09:23 AM

在大多數情況下,人們展示了@Apply的@Apply功能,其中包括Tailwind的單個property實用程序之一(會改變單個CSS聲明)。當以這種方式展示時,@Apply聽起來似乎很有希望。如此明顯

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用