Skip to content

How to keep aspect ratio

Daisho Komiyama edited this page Apr 19, 2023 · 2 revisions

Here's the anatomy of SVG viewBox attribute.

viewBox="0 0 100 100"
         | |  |   |
         x y width height

This is how to keep the original aspect ratio while allowing component consumers to dynamically set size (width and height) in Svelte.

<script lang="ts">
    export let size = 137;
    const aspectRatio = 137 / 22; // 6.2272727272727275
    const height = size / aspectRatio
    // height : size = 22 : 137
    // height : size = 19.27 : 120
    // ^ see? it's keeping the same aspect ratio regardless of `size` value
</script>

<svg
    width={size}
    height={size / aspectRatio}
    viewBox="0 0 137 22"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
>
    <path
        d="M1.13775 2.94106H4.85965L10......."
        fill="#312F36"
    />
</svg>
Clone this wiki locally