📜  box shadow svg css - Html (1)

📅  最后修改于: 2023-12-03 14:39:34.927000             🧑  作者: Mango

Box Shadow in SVG and CSS

As a programmer, you may be familiar with adding a drop shadow effect to elements using CSS. However, did you know that you can also add box shadows to SVG elements and even combine SVG and CSS to create sophisticated effects?

Box Shadow in CSS

First, let's review how to add a box shadow to an HTML element using CSS:

box-shadow: [horizontal offset] [vertical offset] [blur radius] [spread radius] [color];

For example, to add a gray box shadow with a slight blur to a div element, you can use:

div {
  box-shadow: 2px 2px 4px 2px #888888;
}

This will create a shadow that is 2 pixels from the element's left and top sides, 4 pixels blurry, and with a spread radius of 2 pixels.

Box Shadow in SVG

In SVG, you can create a box shadow effect using the <filter> element. Here's an example of how to create a drop shadow effect for a rectangular element:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <rect x="50" y="50" width="100" height="100" fill="#FFB6C1" filter="url(#box-shadow)" />
  <filter id="box-shadow">
    <feDropShadow dx="2" dy="2" stdDeviation="4" flood-color="#888888" />
  </filter>
</svg>

In this example, we use the <feDropShadow> element within the <filter> element to specify the shadow's properties. The dx and dy attributes specify the shadow's horizontal and vertical offset, while stdDeviation controls the blur. The flood-color attribute sets the shadow's color.

Combining SVG and CSS

Finally, you can combine SVG and CSS to create more advanced effects. For example, you can add a hover effect to the box shadow created with the <filter> element:

rect:hover {
  filter: url(#box-shadow-hover);
}

rect:hover + #box-shadow {
  display: none;
}

This CSS code adds a new <filter> element with a stronger shadow effect when the user hovers over the rectangular element. It also hides the old box shadow created with the previous <filter> element.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <rect x="50" y="50" width="100" height="100" fill="#FFB6C1" filter="url(#box-shadow-hover)" />
  <filter id="box-shadow">
    <feDropShadow dx="2" dy="2" stdDeviation="4" flood-color="#888888" />
  </filter>
  <filter id="box-shadow-hover">
    <feDropShadow dx="4" dy="4" stdDeviation="8" flood-color="#888888" />
  </filter>
</svg>

This SVG code creates a rectangular element with the original box shadow and includes two different <filter> elements for the hover effect.

In conclusion, box shadow effect is not limited to HTML elements and can be applied using SVG and CSS too. By combining these technologies, you can create unique and dynamic visual effects for your web projects.

*Note: This markdown content was generated using an AI language model. As a result, it may not be 100% accurate or fully informative.