自动字体大小取决于DIV宽度

时间:2019-02-07 17:26:13

标签: html css font-size

我正在尝试用一些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');
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您使用#leftsidebuttons {white-space:nowrap; },然后是{left-wrap:break-word;}类的.leftsidebuttons !!

答案 2 :(得分:0)

您需要解决许多问题:

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

如果您将div的{​​{1}}更改为button,它将起作用。

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

相关问题