adjusting css font size by vh and vw

2019-04-16 09:48发布

So I have text that I want to automatically resize based on the size of its container. However if I use something like

font-size: 5vw;

it looks good, but when I shrink the page the height starts getting way too small

Is there anyway that I can resize the text based on both vh and vw so, for example, if I just decrease the width of the page the height doesn't decrease too?

like if I only decrease the width of the page, I want the height of the text to stay the same and vice versa.

Basically I want the text to always fit inside the box perfectly and have same proportions no matter what the size of the page/container is?

Is there anyway to base font size on both vh and vw like this in CSS/HTML?

2条回答
We Are One
2楼-- · 2019-04-16 10:19

You can look into the vmin and vmax units.

While 1vw will return 1% of the viewport width and 1vh will return 1% of the viewport height, 1vmin will return 1% of the smallest viewport dimension, be it either the viewport width (vw) or its height (vh). Equally 1vmax will return 1% of whichever viewport dimension is the largest.

In order to have a whole container, including its text, to retain its aspect ratio you will have to apply the same kind of unit to both the container dimensions and its font size.

See the following example in full page mode and play around with the window width and height:

p {
  width: 80vmin;
  font-size: 6vmin;
}
<p>Try resizing both the width and height of the output frame. The &lt;p&gt; element and its contents will both respond to whichever dimension is the smallest.</p>

Note

Internet Explorer 11 and Edge 12 does not support the vmax unit. More on browser support here.

查看更多
虎瘦雄心在
3楼-- · 2019-04-16 10:36

I have been using vw for some time now. I typically use a larger vw for the mobile first (anything under about a 700px viewport). I then adjust everything above that 700px viewport to one a size fits all vw value. That coupled with bootstrap's ease of use flexbox classes gives much less overhead to the css content.

查看更多
登录 后发表回答