2017-03-08 9 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-sizeおよびthe letter-spacing)。私は私の "Hello Plunker"を変更することができ、最後の手紙は、下のdivが終了するところで終わるはずです。

私はあなたがJSを使用して喜んでいる場合は、http://fittextjs.com/は一見の価値があるのjQuery

+0

その内容を親の 'div'の中にラップし、それを' fixed width'に設定します。その後、それを管理することができます。 –

答えて

1

これは醜い答えですが、あなたはCSSにこだわりを予定している場合、それだけでトリックを行う可能性があります。うまくいけば、誰かがより良い方法を指摘できるだろう。

この考えは、text-align: justifyがすべてのテキスト行を最後の1行(またはただ1行の場合は1行)に広げるという事実に依存しています。したがって、少なくとも2行のテキストがあることを確認するために、無用なテキストを追加しています。次に、2行目を隠そうとします。私はこれを大幅に改善することができ確信している:

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

1

必要に応じていくつかのJSを使用できませんが。私はCSSだけで達成できるとは思いません。

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>

関連する問題