Font scaling based on width of container

后端 未结 30 3033
面向向阳花
面向向阳花 2020-11-21 04:35

I\'m having a hard time getting my head around font scaling.

I currently have a website with a body font-size of 100%. 100% of what though? This seems t

30条回答
  •  情歌与酒
    2020-11-21 05:23

    There is a big philosophy for this issue.

    The easiest thing to do would be to give a certain font-size to body (I recommend 10), and then all the other element would have their font in em or rem. I'll give you an example to understand those units. Em is always relative to its parent:

    body{font-size: 10px;}
    .menu{font-size: 2em;} /* That means 2*10 pixels  = 20 pixels */
    .menu li{font-size: 1.5em;} /* That means 1.5*20 pixels = 30 pixels */
    

    Rem is always relative to body:

    body{font-size: 10px;}
    .menu{font-size: 2rem;} /* That means 2*10 pixels = 20 pixels */
    .menu li{font-size: 1.5rem;} /* that means 1.5*10 pixels = 15 pixels */
    

    And then you could create a script that would modify font-size relative to your container width. But this isn't what I would recommend. Because in a 900 pixels width container for example you would have a p element with a 12 pixels font-size let's say. And on your idea that would become an 300 pixels wide container at 4 pixels font-size. There has to be a lower limit.

    Other solutions would be with media queries, so that you could set font for different widths.

    But the solutions that I would recommend is to use a JavaScript library that helps you with that. And fittext.js that I found so far.

提交回复
热议问题