简体   繁体   中英

Increase the width of SVG rect

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM