【问题标题】:Auto font-size depending on DIV width自动字体大小取决于 DIV 宽度
【发布时间】:2019-02-08 02:02:12
【问题描述】:

我正在尝试用一些 HTML 代码替换 JPG 图像。按钮的空白轮廓仍将用于标准按钮以及悬停,但我希望通过代码处理按钮内的文本。

但问题是一些按钮有多个多行的单词,而其他按钮只有几个单词。

我想让按钮的字体大小是动态的而不是设置的,然后也自动换行并进行相应的调整。

我发现这是我想做的事情: Font-size depends on div width and height

但我需要将文本自动换行。

这是我似乎无法正常工作的示例。 https://jsfiddle.net/5L39xq1n/

<div style="text-align:center;padding:20px 0;">DIV Button Test</div>

<div id="buttoncontainer">
    <div id="leftsidebuttons" class="leftsidebuttons">
        Multiple lines because of the number of words
    </div>
    <div id="leftsidebuttons" class="leftsidebuttons">
        Single Line
    </div>
    <div id="leftsidebuttons" class="leftsidebuttons">
        This is another multiple line button
    </div>
</div>

#buttoncontainer { width:175px; height:46px; line-height:46px; }

#leftsidebuttons { white-space:nowrap; }

.leftsidebuttons { color:#d5a200 !important; 
  background-color:blue;
  font-family: Arial, Helvetica, sans-serif;
    font-style:italic; 
  font-weight:700; 
  margin:5px 0;
  text-align:center; 
    word-wrap: break-word; 
}

.leftsidebuttons:hover { color:#ffcc00 !important; 
    background-color:red;
    text-align:center; 
}

var container = $("#buttoncontainer"),
text_container = $("#leftsidebuttons"),
start_size = 16,
container_width = container.width();

text_container.css('font-size', start_size + 'px');

while (text_container.width() > container_width) {
    text_container.css('font-size', start_size--+'px');
}

【问题讨论】:

    标签: html css font-size


    【解决方案1】:

    删除white-space:nowrap 应该可以完成这项工作。

    【讨论】:

      【解决方案2】:

      你使用#leftsidebuttons { white-space:nowrap; } 然后 {word-wrap: break-word;} 用于类 .leftsidebuttons!!

      【讨论】:

        【解决方案3】:

        有很多问题需要解决:

        • 具有相同 id 的多个元素
        • 不要将 div 用作按钮
        • 这种方法很慢,基本上它会尝试每种字体大小,直到适合为止。

        如果您将div 更改为buttonauto,它将起作用。

        https://jsfiddle.net/357d2ka6/1/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-14
          • 2018-03-22
          • 1970-01-01
          • 1970-01-01
          • 2018-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多