简体   繁体   中英

How to make responsive text in SVG that scales to fit container

I have seen many things hinting at this possibility:

That first link is best, which shows how the text scales.

在此处输入图片说明

I have implemented a janky JavaScript version of this functionality, but I want to apply it to a lot of elements and I think SVG would be a better choice.

However, my attempt at copying the code from that first link doesn't end up with the same result, it doesn't work:

 <head> <style> * { padding: 0px; margin: 0px; } /*div*/.ad-wrapper { height: 0; padding-top: 100%; position: relative; } /*svg*/.ad { position: absolute; width: 100%; height: 100%; top: 0; left: 0; background: red; color: black; } </style> </head> <body> <div class="ad-wrapper"> <svg class="ad" xmlns="http://www.w3.org/2000/svg"> <text font-family="'proxima-nova', sans-serif">Mountain</text> </svg> </div> </body> 

Wondering what I'm doing wrong and how to fix it. I would like to have text centered in a responsive box (square even), where the padding on all sides of the text is proportionally the same as it scales up, without the need to use JavaScript at all.

Use always a viewBox attribute. A viewBox="0 0 100 100" will give you a square box. Give the text ax and a y. In this case you may use x="50" y="50" In order to center the text you may use text-anchor:middle;dominant-baseline:middle

 * { padding: 0px; margin: 0px; } /*div*/.ad-wrapper { height: 0; padding-top: 100%; position: relative; } /*svg*/.ad { position: absolute; width: 100%; top: 0; left: 0; background: red; color: black; } text{fill:black;text-anchor:middle;dominant-baseline:middle} 
 <div class="ad-wrapper"> <svg class="ad" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <text x="50" y="50" font-family="'proxima-nova', sans-serif">Mountain</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