简体   繁体   English

如何在SVG中制作可缩放以适合容器的响应文本

[英]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. 我已经实现了此功能的简陋JavaScript版本,但我想将其应用于很多元素,我认为SVG是一个更好的选择。

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. 我想让文本居中于响应框(甚至是正方形)的中心,其中文本各边的填充都按比例缩放,并且按比例放大,而根本不需要使用JavaScript。

Use always a viewBox attribute. 始终使用viewBox属性。 A viewBox="0 0 100 100" will give you a square box. 一个viewBox="0 0 100 100"将为您提供一个方形框。 Give the text ax and a y. 输入文本ax和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 在这种情况下,您可以使用x="50" y="50"为了使文本居中,可以使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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