开发者

Font Size equal to the height of the current container

开发者 https://www.devze.com 2023-04-07 18:34 出处:网络
If I have a div that is x high, how can I make the text inside of it the max it can be assuming that it can only take up one line.

If I have a div that is x high, how can I make the text inside of it the max it can be assuming that it can only take up one line.

开发者_运维技巧While I would prefer a CSS answer, any jquery/javascript answers are accepted just because I need this to work either way :)


Based on Aleks G's comment, this example shows how you would incrementally increase the font size until you'd reached your max:

HTML

<div>
    <span>This is some text</span>
</div>

CSS

div {
  width: 300px;
}

span {
  display: inline-block;   
}

jQuery

var $span = $('span');
var $div = $('div');

while($span.width() < $div.width()){
    $span.css({fontSize: "+=1"});   
}
$span.css({fontSize: "-=1"});  

If you wanted to eliminate any stuttering as the font size was being changed, you could hide the text until the while loop was complete.


Set the font-size and line-height to the same height of the container:

div {
    height:50px;
    font-size:50px;
    line-height:50px;
    border:1px solid red;
}

Demo: http://jsfiddle.net/AlienWebguy/V7f4w/


No way I know of to do that with pure CSS that will be cross browser compatibile. Use javascript and/or jquery to do this. I'll write it out in jquery since its a bit easier:

$("mydiv").css("font-size", $("mydiv").css("height"));
0

精彩评论

暂无评论...
验证码 换一张
取 消