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

前端 未结 4 1648
别跟我提以往
别跟我提以往 2021-01-17 15:34

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 potenti

相关标签:
4条回答
  • 2021-01-17 15:45

    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.

    0 讨论(0)
  • 2021-01-17 15:52

    This is still nearly impossible in CSS only, as the size of each character in different fonts isn't known to us via CSS. There is a jQuery plugin called fitText that handles this sort of thing very nicely.

    0 讨论(0)
  • 2021-01-17 15:55

    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.

    0 讨论(0)
  • 2021-01-17 16:03

    Calc is still in it's infancy in terms of support & usefulness. By design it's really just there for doing simple math, like (100% - 20px). It really won't do the math complex enough to make the calculations possible. You are looking for a solution that will size the text based on the amount of space the letters physically take up horizontally (which depends on the letter's individual sizing) and the amount of space available for the containing div.

    CSS is abstracted away from the actual element's contents, and it has no way to really discern if something currently "fits" or not. It can layout guidelines for how to handle things when they do or don't fit, but it can't adjust itself according to the content like you want it to. (It's not just you, we've all faced this problem or a similar version of it at some point.)

    Check out Chris Coyer's post on what Calc might be handy for: http://css-tricks.com/a-couple-of-use-cases-for-calc/

    0 讨论(0)
提交回复
热议问题