Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure CSS to make font-size responsive based on dynamic amount of characters

Tags:

css

I know that this could be solved fairly easily with Javascript, but I'm only interested in a pure CSS solution.

I want a way to dynamically resize text so that it always fits into a fixed div. Here is the sample markup:

<div style="width: 200px; height: 1em; overflow: hidden;">    <p>Some sample dynamic amount of text here</p>  </div>

I was thinking that maybe this could be possible by specifying the width of the container in ems, and getting the font-size to inherit that value?

like image 883
DMTintner Avatar asked Jan 21 '13 01:01

DMTintner


People also ask

How do I make text size responsive in CSS?

Use the calc() Function to Create Responsive Fonts in CSS We can use the calc() function to make the font size responsive. The result of the function is the value of the property. For example, set the font-size property of body tag to the calc() function. Inside the function, write 0.75em + 1vw .

How do I automatically adjust font size in CSS?

Syntax: font-size-adjust: number|none|initial|inherit; Below are the examples that illustrates the use of font-size-adjust property.


2 Answers

Note: This solution changes based on viewport size and not the amount of content

I just found out that this is possible using VW units. They're the units associated with setting the viewport width. There are some drawbacks, such as lack of legacy browser support, but this is definitely something to seriously consider using. Plus you can still provide fallbacks for older browsers like so:

p {     font-size: 30px;     font-size: 3.5vw; } 

http://css-tricks.com/viewport-sized-typography/ and https://medium.com/design-ux/66bddb327bb1

like image 157
DMTintner Avatar answered Oct 16 '22 01:10

DMTintner


Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.

Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.

<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">  Some sample dynamic amount of text here </div>  

.

.

.

Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.

body {    font-size: 3.2vw; } 
  1. 3.2vw = 3.2% of width of viewport
  2. 3.2vh = 3.2% of height of viewport
  3. 3.2vmin = Smaller of 3.2vw or 3.2vh
  4. 3.2vmax = Bigger of 3.2vw or 3.2vh see css-tricks.com/.... and also look at caniuse.com/....
like image 43
aWebDeveloper Avatar answered Oct 16 '22 00:10

aWebDeveloper