簡體   English   中英

使用純CSS,是否可以使容器的字體大小與其寬度或高度成比例?

[英]Using pure CSS, is it possible to make a container's font-size proportional to its width or height?

為了使字體始終適合其容器,我總是使用Javascript來制作div或某個classfont-size始終等於它們的width並使用font-size定義它們的內部文本元素。

演示: http//jsfiddle.net/pjk8t5kb/

<div class="font-size-equals-width">
    <h1>Here's a headline</h1>
    <p>Here's some paragraph text</p>
</div>

.font-size-equals-width
{
    padding: 5%;
    border: 1px solid black;
}

.font-size-equals-width h1 { font-size: 0.2em; }
.font-size-equals-width p { font-size: 0.1em; }

function scaleFontSize ( ) 
{
   $('.font-size-equals-width').each(function()
   { 
       var thisContainer = $(this); 
       thisContainer.css('font-size', thisContainer.width().toString() + 'px');
   });    
}

$(window).resize(function ( ) 
{
    scaleFontSize();       
});

$(document).ready(function()
{
    scaleFontSize();   
});

我的問題是這是否可以在CSS? 據我所知,唯一的font-size單位是%emptpx ,其中沒有一個連接到容器的widthheight Bootstrap有什么用的嗎? (我總是在我的項目中包含Bootstrap,但我覺得我沒有充分利用它。)

代碼筆: http//codepen.io/anon/pen/pJBdxP

.font-size-equals-width {
  padding: 5%;
  border: 1px solid black;
  width:50%;
  margin: 0 auto;
}

.font-size-equals-width h1 {
  font-size: 2vw;
}

.font-size-equals-width p {
  font-size: 1vw;
}

嘗試這個

希望能幫助到你

好像你想要Viewport Percentage Units: http//dev.w3.org/csswg/css-values/#viewport-relative-lengths

此前回答: 基於容器寬度的字體縮放

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM