stemon
stemon

Reputation: 651

SVG: How to make svg same width as text?

I want to have an svg line underneath a link so that I can animate it. The struggle I am having is to make the svg same width as the text.

a {
  text-decoration: none;
}

.button{
  display: inline-block;
  text-align: center;
}
<a href="" class="button">
    Let's talk about your project
    <span>
        <svg  viewBox="0 0 62 3" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="m0 1h62" fill="none" stroke="#B089F9" stroke-linecap="square" stroke-width=".2"/></svg>
    </span>
</a>

Upvotes: 0

Views: 765

Answers (1)

disinfor
disinfor

Reputation: 11533

The problem is that your SVG is affecting the width of the .button element.

To fix that, give your .button element a position: relative and then make your SVG position: absolute. Your SVG will then only be as wide as the button text.

EDIT I added an animated version. The way SVGs work, you may need to add preserveAspectRatio="none" to the SVG to get it to scale correctly.

div {
  margin: 0 0 50px;
}

.button {
  text-decoration: none;
  display: inline-block;
  text-align: center;
  position: relative;
}

svg {
  position: absolute;
  top: auto;
  bottom: -15px;
  left: 0;
}

.button.animated {
  text-decoration: none;
  display: inline-block;
  text-align: center;
  position: relative;
}

.button.animated svg {
  height: 3px;
  width: 0;
  transition: width .2s ease;
}

.button.animated:hover svg {
  width: 100%;
}
<div>
  <a href="" class="button">
    Let's talk about your project
        <svg viewBox="0 0 62 3" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="m0 1h62" fill="none" stroke="#B089F9" stroke-linecap="square" stroke-width=".2"/></svg>
</a>
</div>

<div>
  <a href="" class="button animated">
    Let's talk about your project
        <svg preserveAspectRatio="none" viewBox="0 0 62 3" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="m0 1h62" fill="none" stroke="#B089F9" stroke-linecap="square" stroke-width=".2"/></svg>
</a>
</div>

Upvotes: 2

Related Questions