Home > Enterprise >  Can an SVG inherit its size from the parent element?
Can an SVG inherit its size from the parent element?

Time:06-24

I'm trying to to switch a Vue/Vuetify app from using the webfont for Material Design Icons to use SVG icons instead.

When using the webfont, an example of a heading that contains an icon is

<template>
  <h1>
    <v-icon>mdi-format-list-bulleted</v-icon>
    My Heading
  </h1>
</template>

The height of the icon automatically matches the heading because the <i> element that is generated for the icon has CSS properties

font-size: inherit;
color: inherit;

After switching to SVG icons, an example of a heading that contains an icon is

<template>
  <h1>
    <v-icon>{{ iconPath }}</v-icon>
    My Heading
  </h1>
</template>

<script>
  import { mdiFormatListBulleted } from '@mdi/js'

  export default {
    data: () => ({
      iconPath: mdiFormatListBulleted
    })
  }
</script>

This generates the following markup instead:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img"
    aria-hidden="true" >
    <!-- path element omitted -->
</svg>

the CSS class has the following properties

.v-icon__svg {
    height: 24px;
    width: 24px;
    fill: currentColor;
}

The fixed icon height of 24px means that the SVG icon doesn't match the heading's height.

Although the <v-icon> component provides a number of props that I can use to change the icon's size, e.g. size, large, small, these will fix the size to a specific value, rather than inheriting the size from the parent element.

Is there a way for an SVG to inherit it's size from it's parent element? More specifically, I want the SVG height and width to be the same as the parent element's height.

Demo

I've created a demo of what happens when you use SVG icons. It takes about 30 seconds for it to load, and you may need to disable 3rd party cookies for it to work.

CodePudding user response:

If you set the height of the SVG to one of the relative units it will match the font-size of the context. You can combine this with vertical-align if necessary.

h1,h2 {
  color: navy;
}

.height-ch {
    height: 1ch;
    fill: currentColor;
}

.height-em {
    height: 1em;
    fill: currentColor;
}

.height-rem {
    height: 1rem;
    fill: currentColor;
}
<h1>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img"
    aria-hidden="true" >
    <path d="M 0 0 L 24 0 L 24 24 L 0 24 Z" />
</svg>
Heading em
</h1>
<h2>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img"
    aria-hidden="true" >
    <path d="M 0 0 L 24 0 L 24 24 L 0 24 Z" />
</svg>
Heading em
</h2>
<h2>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img"
    aria-hidden="true" >
    <path d="M 0 0 L 24 0 L 24 24 L 0 24 Z" />
</svg>
Heading ch
</h2>
<h2>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img"
    aria-hidden="true" >
    <path d="M 0 0 L 24 0 L 24 24 L 0 24 Z" />
</svg>
Heading rem
</h2>

  • Related