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

How Can I Scale an Inline SVG to Fit Its Parent Container?

DDD
Release: 2024-12-10 15:11:11
Original
517 people have browsed it

How Can I Scale an Inline SVG to Fit Its Parent Container?

How to Scale an Inline SVG Element

In certain scenarios, developers may need to dynamically scale an inline SVG image to match the size of its parent container. This can be achieved without referencing an external SVG file and allows for the application of additional CSS styles to the SVG's contents.

To scale an inline SVG, use the following steps:

  1. Specify the Viewbox Attribute:
    Define the image's bounding box within its coordinate system using the viewBox attribute on the SVG element. The values represent the x and y coordinates of the top-left corner and bottom-right corner of the SVG.
  2. Set the Width and Height Attributes:
    Specify the width and height of the SVG as it should appear within the containing page using the width and height attributes. These values dictate how the SVG scales proportionally.

For example, the following code will render a triangle within a 10px by 20px bounding box, which will then be scaled to fit its parent container:

svg {
  border: 1px solid blue;
}

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

By specifying the coordinates within the SVG independently of its scaled size, the image will maintain its proportions and render correctly regardless of its container's size.

The above is the detailed content of How Can I Scale an Inline SVG to Fit Its Parent Container?. 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