2015-10-06 301 views
0

我有一段文字。當文本長度增加時,我不想溢出多餘的頁面。總是需要打印一頁。CSS中的自動縮放字體大小

是否有可能使用css自動縮放文本的字體大小,在文本大小大於div大小的div中?

該文本將由用戶編寫。我對文本長度沒有任何想法。但我不想讓他們使用多於一頁的頁面。可以設置div的大小,但不能設置文本的長度。什麼是最好的方法呢?

+0

如果我們減小字體大小就好了嗎? –

+0

用JavaScript它是:) – nowhere

+0

哦是的..純粹的CSS我懷疑。如果它的Javascript可能我可以給你一些代碼片段:) –

回答

1

Per your comment你是開放使用JavaScript,因此提出了一個JavaScript解決方案(實際使用jQuery)。希望你明白,只有CSS才能做到這一點。

您只需要爲height定義您的閾值。例如,如果您決定需要在最大高度爲100pxp中容納文字,則循環並繼續減小font-size,直到達到閾值高度。

事情是這樣的:

var threshold = 100, /* define height to restrict */ 
    p = $('#p'), /* your element depending on whatever selector */ 
    fs = parseInt(p.css('font-size')); /* get the current font size */ 

while (p.height() > threshold) { /* while height is more than threshold */ 
    p.css({'font-size': fs-- }); /* reduce the font-size */ 
} 
p.height(threshold); /* adjust the final height to clean up */ 

您可能需要在循環之後調整最終高度一點點。

演示小提琴:http://jsfiddle.net/abhitalks/ab6m7yh1/2/

演示片段

var threshold = 100; 
 

 
$('p').each(function() { 
 
    var $self = $(this), 
 
\t \t fs = parseInt($self.css('font-size')); 
 
    
 
    while($self.height() > threshold) { 
 
     $self.css({'font-size': fs-- }); 
 
    } 
 
    $self.height(threshold); 
 
});
p { font-size: 2em; width: 320px; height: auto; border: 1px solid #ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> 
 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> 
 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

+0

非常感謝你:) –

0

您可以使用引導程序,讓您的自適應網站 - 與col-md-xx,引導會自動更改段落的字體大小,檢查了這一點: http://getbootstrap.com/css/#responsive-utilities

以另一種方式 - 你可以添加這樣一個類似的代碼您的樣式表:

@media (min-width: 320px) and (max-width: 480px) { 
    .div-font{font-size:20px} 
} 

記得設置最大和最小寬度,並更改選擇的名稱

0

您可以使用CSS媒體查詢FO R該比如你可以設置每個標籤響應

@media only screen and (max-width: 768px) { 

    h1 { 
     font-size: 2,5em; 
    } 

    h2 { 
     font-size: 2em; 
    } 

    p{ 
     font-size:1,8em 
    } 

}