2016-04-18 12 views
1

これが基本的なように、私はこの動作を得ることができません。親の高さを子要素の相対位置と絶対位置に一致させる

簡単に言えば、私は親要素の相対位置を持っています。 次に、子要素 - 絶対位置。

子が親よりも高い場合、親の高さをどのように一致させることができますか。意味、親を拡張する方法。ここで

あなたは、あなたのファイルに次のコードを追加して、子クラスからの高さを削除してくださいjqueryの使用できる場合、私は https://jsfiddle.net/wthwawcv/

<div class="parent"> 
    dsfsdfsdfsdf<br> 
    hellow .. line 2 <br> 
    hello .. line 3 
    <div class="child"> 
    this is the child element to be diaplayed 
    </div> 
</div> 


.parent { 
    width:100%; 
    background: #ff0000; 
    width:200px; 
    position: relative; 
    overflow: hidden; 
} 

.child { 
    width:40px; 
    height:100px; 
    background: #ffff00; 
    position: absolute; 
    right: 0; 
    top: 0; 
} 
+1

これは、子供がいる場合は、純粋なHTML/CSSでは不可能です絶対/固定配置。回避策については、このスタックの質問をチェックしてください:[絶対/固定子を持つ親コンテナの自動高さ](http://stackoverflow.com/questions/9061520/auto-height-on-parent-container-with-absolute-fixed-子供) –

答えて

1

FIDDLE DEMO作業とされてclearfixハック:

.parent { 
 
    width:100%; 
 
    background: #ff0000; 
 
    width:200px; 
 
    position: relative; 
 
} 
 
.parent:after { 
 
    content: '.'; 
 
    color: transparent; 
 
    clear: right; 
 
    overflow: hidden; 
 
    display: block; 
 
    height: 0; 
 
} 
 

 
.child { 
 
    float: right; 
 
    width:40px; 
 
    background: #ffff00; 
 
}
<div class="parent"> 
 
<div class="child"> 
 
    this is the child element to be displayed 
 
    </div> 
 
    Child is<br> 
 
    longer than<br> 
 
    parent content. 
 
</div> 
 
<br> 
 
<div class="parent"> 
 
<div class="child"> 
 
    child 
 
    </div> 
 
    Child is<br> 
 
    shorter than<br> 
 
    parent content. 
 
</div>

+0

こんにちは..返事ありがとうございます。これは私が探していたものに近いです。しかし。親がパディングを持っている場合はどうすれば使用できますか?私はまだ、親の高さ全体をカバーするために子供を必要としていました(したがって私は絶対的な位置を最初に使用しました)。 – Archer

+0

あなたの子供に負のマージンとしてパディング値を追加します。もちろん、上/右/下側のみにしてください。 – Paul

+0

はい..それを正確に試しましたが、何らかの理由で、子の幅が0pxのときに親が長すぎるようになります。しかし、私はhideのCSSで 'display:none;'を行うと、通常の高さに戻ります。しかし、私は、私が使用しているトランジションを緩めます(別の要素をクリックすると子ウィンドウ0pxと30pxの幅を切り替える) – Archer

0

で探しています何でJSのフィドルです。ここ は、あなたがfloatを使用することができ、代わりに、絶対位置の

var min_parent_height = jQuery(".child").height()+"px"; 
console.log(min_parent_height); 
jQuery(".parent").css({'min-height':min_parent_height}); 
関連する問題