Home >Web Front-end >CSS Tutorial >How Do I Make Inline SVGs Scale Proportionally with Their Parent Container?

How Do I Make Inline SVGs Scale Proportionally with Their Parent Container?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 08:47:10527browse

How Do I Make Inline SVGs Scale Proportionally with Their Parent Container?

Scaling Inline SVGs Proportionally with Parent Container

Having an inline SVG scale in proportion to its parent container is a convenient way to dynamically resize SVG content. This is desirable when you need to embed SVG graphics within HTML elements and ensure they scale appropriately. Here's how to achieve this:

<svg viewBox="0 0 100 50">
  <polygon fill="red" points="0,0 100,0 50,50" />
</svg>

In this example, the SVG element has a width of 100 and a height of 50, as defined by the viewBox attribute. The polygon element represents a triangle that spans the entire width and height of the SVG.

The viewBox attribute specifies the coordinates of the SVG's content. In this case, the coordinates range from 0 to 100 horizontally and 0 to 50 vertically. Even if you resize the SVG element using CSS, the triangle will always fill the entire viewBox area.

svg {
  width: 300px; /* Can be any value */
  height: auto; /* Automatically scales height */
}

By setting the SVG element's width, we can specify the desired size of the containing element. The height will be automatically adjusted to maintain the aspect ratio of the SVG, ensuring the triangle remains proportionally scaled.

This approach allows you to embed SVGs within HTML elements and control their size dynamically without using external files or sacrificing styling options.

The above is the detailed content of How Do I Make Inline SVGs Scale Proportionally with Their 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