Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - calc() on font-size - changing font size based on container size

Tags:

css

I have a situation where I have a container element (div) that contains text. This text will sometimes be really large - not paragraph large, but it can potentially exceed the width of the text.

Obviously, in most situations it will just knock parts of the text to the next line, but I wanted to see if calc() can be used on font-size to change the size of the font to make sure it is always fitting within the bounds of the div it is in. Can this be done?

.name { width: 500px; font-size: 64px; }

<span class="name">Sometimes it is short</span>

<span class="name">Sometimes it is going to be really long, and people put long names</span>

I could just limit the number of letters people can use for a name - and to an extent I will, but I am curious to see if this can even be accomplished.

I found this post to do it with Javascript, but that was a long time ago, and I think CSS3 has a lot of new things that may let this be accomplished without any scripting. AutoFill

like image 369
Ciel Avatar asked Apr 08 '14 18:04

Ciel


People also ask

How do I automatically adjust font-size in CSS?

The font-size-adjust property of CSS tells the browser to adjust the font size of the text to the same size regardless of font family. When the first chosen font is not available, the font-size-adjust property allows you more control over the font size.

Can you use Calc on font-size?

Using viewport units and calc() , we can have font-size (and other properties) adjust their size based on the size of the screen.

How do I make text fit in a box in CSS?

You have to set 'display:inline-block' and 'height:auto' to wrap the content within the border.


2 Answers

Here a possible solution:

http://codepen.io/CrocoDillon/pen/fBJxu

p {
  margin: 0;
  font-size: calc(4vw + 4vh + 2vmin);
  /* See:
   * http://codepen.io/CrocoDillon/pen/jgmwt
   * For some math behind this
   */
}

Font-size is calculated with available size using a function that is not perfect, but may be adjusted to work well in some cases.

like image 195
Julio Rabadan Avatar answered Oct 03 '22 01:10

Julio Rabadan


Just a clarification:

if you use something like:

font-size: -webkit-calc(100% + 30px);
font-size:        -calc(100% + 30px);

what this does is add 30px to the 100% default font size, it can't be linked to the container width.

Although, you can do math there like:

font-size: -webkit-calc( 100% * 0.09479166667 - 6.666666669px );
font-size:        -calc( 100% * 0.09479166667 - 6.666666669px );

... but it will just calculate it against the 1em.

like image 45
ludiccc Avatar answered Oct 03 '22 02:10

ludiccc