2017-03-01 137 views
3

僅使用CSS,是否可以讓一行文本的大小盡可能大以適應div的寬度和高度而不用換行?動態調整字體大小

vh和vw單位似乎很有前途,但它似乎不是答案。

+0

沒有,沒有。有一些類似的JS/jQuery插件 – Johannes

+0

好問題,看看這個:http://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container –

回答

0

您可以使用javaScript並使字體大小越來越小(或越來越大),直到具有文本的子元素的高度符合父元素的高度。更改文本的font-size和容器的widthheight以查看效果。

var samp = document.getElementById('samp'); 
 

 
fitFont(samp); 
 

 

 
function fitFont(elem){ 
 
    var child = elem.children[0]; 
 
    var getFontSize = parseFloat(window.getComputedStyle(child).getPropertyValue('font-size')); 
 
    
 
    while(child.offsetHeight>elem.clientHeight){ 
 
    getFontSize -= .1; 
 
    child.style.fontSize = getFontSize + 'px'; 
 
    if(child.offsetHeight<=elem.clientHeight){ 
 
     child.style.visibility = 'visible'; 
 
     return; 
 
    } 
 
    } 
 
    while(child.offsetHeight<elem.clientHeight){ 
 
    getFontSize += .1; 
 
    child.style.fontSize = getFontSize + 'px'; 
 
    if(child.offsetHeight>=elem.clientHeight){ 
 
     child.style.visibility = 'visible'; 
 
     return; 
 
    }  
 
    } 
 
    
 
}
#samp { 
 
    background-color:white; 
 
    width:280px; 
 
    height:100px; 
 
    border:solid 2px #33aaff; 
 
} 
 

 
#samp span { 
 
    display: inline-block; 
 
    visibility:hidden; 
 
    font-size:50px; 
 
}
<div id="samp"> 
 
    <span>text is bigger now and goes outside of div text is bigger now and goes outside of div text is bigger now and goes outside of div text is bigger now and goes outside of div 
 
    </span> 
 
</div>

0

你要得到的是設置在外部容器&文本容器大衆和VH值最接近的事,和文本容器的字體大小VMIN。

.outer { 
 
    width: 100vw; 
 
    height: 100vh; 
 
} 
 

 
.text { 
 
    width: 30vw; 
 
    height: 30vh; 
 
    border: solid 1px #269abc; 
 
    font-size: 10vmin; 
 
}
<div class='outer'> 
 

 
    <p class='text'>This is text</p> 
 

 
</div>

除此之外,你會需要使用JavaScript/jQuery的

+0

錯過了'沒有包裝' - 哎呀。簡短的回答 - 不。目前不可能。 CSS變量正在起作用 - 所以可能很快就是了。 https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables – Inkdot