douzhi2760 2011-09-14 18:05
浏览 25
已采纳

查找动态宽度的最大字体大小

I'm using SASS/SCSS and want to create a @function/@mixin which will figure the max possible font-size for a container, given a dynamic width.

For example:

<body style="font-size: 10px;">
    <div style="width: 960px;"> <!--This width is dynamic-->
        <span style="font-size: 12.3em">Patrick Rocks</span>
    </div>
</body>

The unknown variable in this equation is the font-size on the <span> tag. I set it to 12.3em which would be 123px (relative to the font-size of the <body> tag), but that could change depending on letter-spacing font-family or other aspects. Perhaps because of the complexity of this it would be best served to calculate this with JavaScript, or PHP.

  • 写回答

2条回答 默认 最新

  • dounie0889 2011-09-14 22:28
    关注

    I've worked it through and found a solution which fits my needs. The solution only works if the following is known.

    • The exact text being used
    • The font being used
    • The default width based on the parent font-size

    DEMO: http://wecodesign.com/demos/stackoverflow-7420897.htm

    SCSS:

    $logoDefaultWidth: 76; /*Pixels*/
    
    @function getFontSize($newLogoWidth) {
        $fontSize: $newLogoWidth/$logoDefaultWidth;
        @return #{$fontSize}em;
    }
    @function pxToEm($px) {
        @return #{$px/10}em;
    }
    body {
        font-size: 10px;
    }
    .logo {
        width: pxToEm($logoDefaultWidth);
    }
    .logo.s960 {
        font-size: getFontSize(960);
    }
    .logo.s480 {
        font-size: getFontSize(480);
    }

    HTML:

    <div class="logo s960">Patrick Rocks</div>
    <div class="logo s480">Patrick Rocks</div>
    

    TODO:

    This solution has a known issue with WebKit (Chrome/Safari) browers. WebKit browsers render @font-face font's much thicker than they should, thus making the $logoDefaultWidth incorrect. I'm working on trying to find out how to stop WebKit from making the font so thick, or on a separate calculation for WebKit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错