Home >Web Front-end >CSS Tutorial >How Can I Make an Inline SVG Scale with Its Parent Container?

How Can I Make an Inline SVG Scale with Its Parent Container?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 21:49:10377browse

How Can I Make an Inline SVG Scale with Its Parent Container?

Scaling Inline SVG with its Parent Container

Incorporating inline SVG elements into HTML code offers the advantage of styling them with CSS. However, scaling such SVG elements to match the dimensions of their parent container can be a challenge.

Solution

To scale an inline SVG with its parent container, it is necessary to utilize the viewBox attribute in conjunction with the width and height attributes:

  1. viewBox attribute: This attribute defines the bounding box of the SVG image within its own coordinate system. It establishes the aspect ratio and initial dimensions of the SVG image. By setting this attribute, you can specify the coordinates within the SVG image independently of its scaled size.
  2. width and height attributes: These attributes specify the width and height of the SVG element within the containing page. They control the size of the SVG image as it appears on the page. By setting these attributes relative to the container's dimensions (e.g., using percentages), you can scale the SVG image proportionally.

For example, consider the following code:

<svg viewBox="0 0 123 456" width="100%" height="100%">
  <polygon fill="red" stroke-width="0" points="0,10 20,10 10,0" />
</svg>

In this example, the SVG image with a native size of 123px by 456px is scaled to fill the entire container. The viewBox attribute defines the coordinates of the polygon within the SVG image itself, while the width and height attributes scale the SVG image to the dimensions of the container. As a result, the polygon renders as a 100% wide red triangle within the container.

The above is the detailed content of How Can I Make an Inline SVG Scale with Its Parent Container?. For more information, please follow other related articles on the PHP Chinese website!

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