简体   繁体   English

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

[英]Auto font-size depending on DIV width

I'm trying to replace JPG images with some HTML code. 我正在尝试用一些HTML代码替换JPG图像。 The blank outline of the buttons will still be used for the standard button, plus the hover, but I want the text within the button to be handled via code. 按钮的空白轮廓仍将用于标准按钮以及悬停,但是我希望按钮内的文本通过代码进行处理。

But the issue is that some of the buttons have multiple words with multiple lines, where-as others are only a couple words. 但是问题在于某些按钮中的多个单词带有多行,而其他按钮只是几个单词。

I'd like to get the font-size for the buttons to be dynamic and not set and then also word-wrap and adjust accordingly. 我想让按钮的字体大小是动态的而不是设置,然后自动换行并相应地进行调整。

I found this which sort-of does what I'd like: Font-size depends on div width and height 我发现这是我想要的: 字体大小取决于div的宽度和高度

But I need to the text to word-wrap. 但是我需要对文本进行自动换行。

Here's my example which I cant seem to get to work properly. 这是我的示例,我似乎无法正常工作。 https://jsfiddle.net/5L39xq1n/ 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');
}

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

you use #leftsidebuttons { white-space:nowrap; 您可以使用#leftsidebuttons {white-space:nowrap; } and then {word-wrap: break-word;} for the class .leftsidebuttons!! },然后是{.wrap:break-word;}类的.leftsidebuttons !!

There are many problem that you would need to fix: 您需要解决许多问题:

  • multiple element with same id 具有相同ID的多个元素
  • don't use div for button 不要使用div作为按钮
  • that approach is very slow, basically it tries each font size until it fits. 这种方法非常慢,基本上会尝试每种字体大小直到适合为止。

if you change the div to button with auto it will work. 如果您使用autodiv更改为button ,它将起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM