Reputation: 3069
Is it possible to increase the width
of a <rect>
while keeping the height
unchanged?
Use case:
There are different svg
shapes that contain text like the one in the below example. Depending on the inputs this text may change. If the text is too long,
I want to increase the width to match the width of the text.
<svg viewBox="0 0 300 100" width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" stroke="red" stroke-width="3px" fill="white"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Hello World</text>
</svg>
In the above example, the visible size of the <rect>
is 300x100 pixels.
If I want to keep the visible height
and increase the width
,
I found that I can increase the width
value of all svg->width
, svg->viewBox->width
and rect->width
attributes.
<svg viewBox="0 0 400 100" width="400px" height="100px">
<rect x="0" y="0" width="400" height="100" stroke="red" stroke-width="3px" fill="white"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Hello World</text>
</svg>
Could this go wrong? Is there a better way?
Upvotes: 0
Views: 1578
Reputation: 153
SVGs are amazing when it comes to filling the box that you give it. Simply create a div container with the required width and height styles and then put the svg inside of it set at 100% width and height. and do the same with each graphic element.
Keep in mind that using this method means you will more than likly need to adjust the padding of the div to place the svg where you need it.
<div style="width:600px; height:150px;">
<svg width="100%" height="100%">
<rect x="0" y="0" width="100%" height="100%" stroke="red" stroke-width="3px" fill="white"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Hello World</text>
</svg>
</div>
<br/>
<div style="width:100px; height:25px;">
<svg width="100%" height="100%">
<rect x="0" y="0" width="100%" height="100%" stroke="red" stroke-width="3px" fill="white"/>
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Hello World</text>
</svg>
</div>
Upvotes: 2