Home > Web Front-end > CSS Tutorial > How Do I Scale Inline SVGs to Fit Their Parent Containers Using `viewBox`, `width`, and `height`?

How Do I Scale Inline SVGs to Fit Their Parent Containers Using `viewBox`, `width`, and `height`?

DDD
Release: 2024-12-31 00:25:13
Original
338 people have browsed it

How Do I Scale Inline SVGs to Fit Their Parent Containers Using `viewBox`, `width`, and `height`?

Scaling Inline SVGs with Parent Containers

When working with inline SVG (Scalable Vector Graphics) elements, one often encounters the need to scale the SVG to match the dimensions of its parent container. While it's possible to achieve scaling by referencing an external SVG file, this approach can limit the ability to style the SVG using CSS. Therefore, a more desirable solution is to scale inline SVGs directly.

Defining Image Coordinates with viewBox and Scaling with Width/Height

To define the internal coordinates of the SVG image and determine how it scales, employ the following attributes:

  • viewBox: Defines the bounding box of the image in its own coordinate system.
  • width: Width of the SVG in units relative to the containing page.
  • height: Height of the SVG in units relative to the containing page.

For example, consider the following inline SVG with a red triangle:

<svg width="10" height="20">
    <polygon fill="red" stroke-width="0" points="0,10 20,10 10,0" />
</svg>
Copy after login

Here, we have:

  • viewBox (0, 0, 20, 10): Specifies that the SVG has a rectangular bounding box with a width of 20 units and a height of 10 units.
  • width (10): Specifies that the SVG should be 10 units wide relative to the containing page.
  • height (20): Specifies that the SVG should be 20 units high relative to the containing page.

This SVG will render as a 10px wide and 20px high red triangle.

The above is the detailed content of How Do I Scale Inline SVGs to Fit Their Parent Containers Using `viewBox`, `width`, and `height`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template