2017-03-08 102 views
1

我有以下的html:的CSS H1匹配的div寬度

<!DOCTYPE html> 
<html> 
    <body> 
    <h1 style="margin-bottom: 0;">Hello Plunker!</h1> 
    <div style="background-color: red; height: 100px; width: 250px;"></div> 
    </body> 
</html> 

基本上我想給我的H1一個width說裏面的文字應該佔據不管我添加或刪除一個字(適應根據它的font-sizethe letter-spacing)。我可以更改我的「Hello Plunker」,最後一個字母應該在下面的div完成。

如果需要的話,但不是jQuery的

+0

將該內容包裝在父'div'中並將其設置爲「固定寬度」。然後你可以管理它。 –

回答

1

這是一個醜陋的答案,但如果你打算堅持CSS它可能只是做的伎倆。但希望有人能夠指出一個更好的方法。

這個想法依賴於這樣一個事實,text-align: justify將分散所有文本行,但最後一行(或只有一行的情況下)。因此,我們添加了一些無用的文本,以確保至少有兩行文本。然後,我們試圖隱藏第二行。我敢肯定,這可以改進:

h1 { 
 
    width: 250px; 
 
    height: 1.4em; 
 
    margin-bottom: 0; 
 
    background-color: green; 
 
    text-align: justify; 
 
} 
 

 
h1 span { 
 
    visibility: hidden; 
 
    display:inline-block; 
 
    line-height: 0px; 
 
} 
 

 
div { 
 
    background-color: red; 
 
    height: 100px; 
 
    width: 250px; 
 
}
<h1>Hello Plunker<span>make sure there are two lines, pretty please?</span></h1> 
 
<div></div>

您可以編輯jsfiddle here。說實話,我想使用JavaScript會更好。

+0

這對於基於css的解決方案來說是一個好的開始 – Scipion

0

只是一個使用transform:scale(jQueryCalc)的想法 - 使內容適合其父母innerWidth。

$(document).ready(function() { 
 
    $(".fit").each(function() { 
 
    $(this).css("transform", "scale(" + ($(this).parent().innerWidth()/$(this).width()) + ")"); 
 
    }); 
 
});
.container { 
 
    background-color: red; 
 
    height: 70px; 
 
    width: 250px; 
 
    display: inline-block; 
 
    position: relative; 
 
    overflow: hidden; 
 
} 
 

 
.fit{ 
 
    display: block; 
 
    color: #FFF; 
 
    float: left; 
 
    transform-origin: left top; 
 
    white-space: nowrap; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <h1 class="fit">Hello Plunker!</h1> 
 
</div> 
 
<div class="container"> 
 
    <span class="fit">Well this should work</span> 
 
</div> 
 
<div class="container"> 
 
    <span class="fit">Well this should work; Well this should work</span> 
 
</div> 
 
<div class="container"> 
 
    <span class="fit">Well this should work; Well this should work; Well this should work; Well this should work</span> 
 
</div>