Neil
Neil

Reputation: 2519

SVG that scales with text width

I'm trying to build a simple banner in SVG that will scale width as the text inside it is filled.

Here is my current code:

#container {
    height: 60px;
    position: relative;
}

#container > svg {
    width: 100%;
    height: 100%;
}

#container > p {
    position: absolute;
    left: 0;
    margin: 5% 10%;
    text-align: center;
    color: white;
}

And the HTML:

<div id="container">
    <span>Strawberry Mango</span>
    <svg viewBox="0 0 10 10" preserveAspectRatio="none">
        <path d="M 0,0 L 10,0 9.5,5 10,10 0,10 0.5,5 z" fill="black"></path>
        <path d="M 0.25,0.75 L 9.75,0.75 9.3,5 9.75,9.25 0.25,9.25 0.75,5 z" fill="orange"</path>
        </svg>
</div>

Which produces a banner that is 100% width of the parent element, but I would like it to scale to the size of the p tag if it is possible.

Here is a fiddle of it

Upvotes: 0

Views: 346

Answers (1)

Zach Saucier
Zach Saucier

Reputation: 25994

Try giving #container display:inline-block so it shrinks to its children, then make the svg have position:absolute instead of the paragraph and also give it z-index:-1; to put it behind the paragraph. This is because your SVG element was defaulting to 300px, which you don't want to happen

Demo

Upvotes: 1

Related Questions