2つのサイドバイサイドDivを同じ高さに保つにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2997767

質問

私は2つのdivを並べて持っています。それらの高さが同じであることを望み、それらの1つがサイズを変更する場合は同じままです。しかし、私はこれを理解することはできません。アイデア?

私の混乱した質問を明確にするために、私は両方のボックスを常に同じサイズにしたいので、テキストがそこに配置されているために成長する場合、もう1つは高さに合わせて成長する必要があります。

<div style="overflow: hidden">
    <div style="border:1px solid #cccccc; float:left; padding-bottom:1000px; margin-bottom:-1000px">
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
    </div>
    <div style="border:1px solid #cccccc; float:left; padding-bottom:1000px; margin-bottom:-1000px">
        Some content!
    </div>
</div>

役に立ちましたか?

解決

FlexBox

FlexBoxでは、単一の宣言です。

.row {
  display: flex; /* equal height of the children */
}

.col {
  flex: 1; /* additionally, equal width */
  
  padding: 1em;
  border: solid;
}
<div class="row">
  <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
  <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad omnis quae expedita ipsum nobis praesentium velit animi minus amet perspiciatis laboriosam similique debitis iste ratione nemo ea at corporis aliquam.</div>
</div>

古いブラウザにはプレフィックスが必要になる場合があります ブラウザのサポート.

他のヒント

これは多くの人が遭遇した一般的な問題ですが、幸いなことにいくつかの賢い心は エド・エリオットは彼のブログにあります オンラインでソリューションを投稿しました。

基本的にあなたがしていることは、両方のdiv/列を作ることです とても Aを追加することで背が高い padding-bottom: 100% そして、「ブラウザをトリック」して、彼らがそれほど背が高くないと考えて margin-bottom: -100%. 。エド・エリオットが彼のブログで説明した方が良いです。これには多くの例も含まれています。

.container {
    overflow: hidden;
}
.column {
    float: left;
    margin: 20px;
    background-color: grey;
    padding-bottom: 100%;
    margin-bottom: -100%;
}
<div class="container">

    <div class="column">
        Some content!<br>
        Some content!<br>
        Some content!<br>
        Some content!<br>
        Some content!<br>
    </div>

    <div class="column">
        Something
    </div>

</div>

これは、CSSが実際に解決策を持っていなかった領域です。 <table> タグ(またはCSSを使用してそれらを偽造します display:table* 値)、それが「同じ高さの要素を維持する」唯一の場所であるため、実装されました。

<div style="display: table-row;">

    <div style="border:1px solid #cccccc; display: table-cell;">
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
    </div>

    <div style="border:1px solid #cccccc;  display: table-cell;">
        Some content!
    </div>

</div>

これは、Firefox、Chrome、Safariのすべてのバージョン、少なくともバージョン8のオペラ、およびバージョン8のIEで機能します。

jqueryを使用します

jQueryを使用すると、非常にシンプルなワンラインスプリクトでそれを行うことができます。

// HTML
<div id="columnOne">
</div>

<div id="columnTwo">
</div>

// Javascript
$("#columnTwo").height($("#columnOne").height());

CSSを使用します

これはもう少し面白いです。テクニックは呼ばれます フェイク列. 。多かれ少なかれあなたは実際に設定しません 実際 高さは同じですが、グラフィカルな要素をリグアップするので、 見る 同じ高さ。

誰も(非常に古いが信頼できる)絶対的な列のテクニックに言及していないことに驚いています。http://24ways.org/2008/absolute-columns/

私の意見では、それは偽の列と1つの真のレイアウトのテクニックの両方よりもはるかに優れています。

一般的な考え方は、との要素です position: absolute; 持っている最寄りの親要素に対して位置します position: relative;. 。次に、両方を割り当てることにより、列を伸ばして100%の高さを埋めます top: 0px;bottom: 0px; (または実際に必要なピクセル/パーセンテージは何でも)例を示します。

<!DOCTYPE html>
<html>
  <head>
    <style>
      #container
      {
        position: relative;
      }

      #left-column
      {
        width: 50%;
        background-color: pink;
      }

      #right-column
      {
        position: absolute;
        top: 0px;
        right: 0px;
        bottom: 0px;
        width: 50%;
        background-color: teal;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="left-column">
        <ul>
          <li>Foo</li>
          <li>Bar</li>
          <li>Baz</li>
        </ul>
      </div>
      <div id="right-column">
        Lorem ipsum
      </div>
    </div>
  </body>
</html>

JQueryのEquary Heightsプラグインを使用して達成できます。このプラグインは、他とまったく同じ高さのすべてのdivを作成します。それらの1つが成長し、もう1つが成長する場合。

ここに実装のサンプル

Usage: $(object).equalHeights([minHeight], [maxHeight]);

Example 1: $(".cols").equalHeights(); 
           Sets all columns to the same height.

Example 2: $(".cols").equalHeights(400); 
           Sets all cols to at least 400px tall.

Example 3: $(".cols").equalHeights(100,300); 
           Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.

これがリンクです

http://www.cssnewbie.com/equalheights-jquery-plugin/

使用できます フェイク列.

基本的に、コンテンディングDIVの背景画像を使用して、2つの等しい高さをシミュレートします。この手法を使用すると、容器に影、丸い角、カスタムボーダー、その他のファンキーなパターンを追加することもできます。

ただし、固定幅のボックスでのみ動作します。

すべてのブラウザで適切にテストされ、適切に機能しています。

このまさに答えを探している間、このスレッドを見つけました。私はちょうど小さなjQuery機能を作りました、これが役立つことを願っています、魅力のように機能する:

JavaScript

var maxHeight = 0;
$('.inner').each(function() {
    maxHeight = Math.max(maxHeight, $(this).height());
});
$('.lhs_content .inner, .rhs_content .inner').css({height:maxHeight + 'px'});

HTML

<div class="lhs_content">
    <div class="inner">
        Content in here
    </div>
</div>
<div class="rhs_content">
    <div class="inner">
        More content in here
    </div>
</div>

この質問は6年前に尋ねられましたが、それでも簡単な答えを与えることは価値があります FlexBox 最近のレイアウト。

次のCSSを父親に追加するだけです <div>, 、 それが動作します。

display: -webkit-flex;
display: flex;
flex-direction: row;
align-items: stretch;

最初の2行は、FlexBoxとして表示されると宣言します。と flex-direction: row 子供が列に表示されることをブラウザに伝えます。と align-items: stretch すべての子供の要素が同じ高さに伸びるという要件を満たします。

の1つを気にしない場合 divsはマスターであり、両方の高さを口述する divsこれがあります:

フィドル

何があっても、 div 右側の高さに一致するように右側の拡張またはスクイッシュ&オーバーフロー div 左に。

両方 divsは容器のすぐ近くの子供でなければならず、その中の幅を指定する必要があります。

関連するCSS:

.container {
    background-color: gray;
    display: table;
    width: 70%;
    position:relative;
}

.container .left{
    background-color: tomato;
    width: 35%;
}

.container .right{
    position:absolute;
    top:0px;
    left:35%;
    background-color: orange;
    width: 65%;
    height:100%;
    overflow-y: auto;
}

私はこれを達成するために擬似要素を使用するのが好きです。コンテンツの背景として使用して、スペースを埋めることができます。

これらのアプローチを使用すると、列、境界などの間にマージンを設定できます。

.wrapper{
  position: relative;
  width: 200px;
}
.wrapper:before,
.wrapper:after{
  content: "";
  display: block;
  height: 100%;
  width: 40%;
  border: 2px solid blue;
  position: absolute;
  top: 0;
}
.wrapper:before{
  left: 0;
  background-color: red;
}
.wrapper:after{
  right: 0;
  background-color: green;
}

.div1, .div2{
  width: 40%;
  display: inline-block;
  position: relative;
  z-index: 1;
}
.div1{
  margin-right: 20%;
}
<div class="wrapper">
  <div class="div1">Content Content Content Content Content Content Content Content Content
  </div><div class="div2">Other</div>
</div>

CSSグリッドウェイ

これを行う現代の方法(これも、 <div class="row"></div>- 2つのアイテムごとにwrapper)は、CSSグリッドを使用することです。これにより、アイテムの行/列間のギャップを簡単に制御できます。

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* or simply "1fr 1fr;" */
  grid-row-gap: 10px; 
  grid-column-gap: 10px;
}

.grid-item {
  background-color: #f8f8f8;
  box-shadow: 0 0 3px #666;
  text-align: center;
}

.grid-item img {
  max-width: 100%;
}
<div class="grid-container">
  <div class="grid-item">1 <br />1.1<br />1.1.1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3
    <img src="https://lorempixel.com/420/320/abstract/1/Sample" alt="" />
    3.1
  </div>
  <div class="grid-item">4</div>
  <div class="grid-item">5 <br />1.1<br />1.1.1</div>
  <div class="grid-item">6<img src="https://lorempixel.com/400/300/abstract/" alt="" />
    6.1</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9 <br />1.1<br />1.1.1</div>
  <div class="grid-item">10</div>
  <div class="grid-item">11
    <img src="https://lorempixel.com/420/320/abstract/1/Sample" alt="" />
    11.1
  </div>
  <div class="grid-item">12</div>
</div>

上記のほぼすべてのメソッドを試しましたが、FlexBoxソリューションはSafariで正しく動作せず、グリッドレイアウトメソッドは古いバージョンのIEで正しく機能しません。

このソリューションはすべての画面に適合し、クロスブラウザー互換です。

.container {margin:15px auto;}
.container ul {margin:0 10px;}
.container li {width:30%; display: table-cell; background-color:#f6f7f7;box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.25);}

@media (max-width: 767px){
    .container li { display: inline-block; width:100%; min-height:auto!important;}
}

上記の方法はセルの高さに等しくなり、モバイルやタブレットなどの小さな画面では、 @media 上記の方法。

JQueryを使用してこれを簡単に実現できます。

CSS

.left, .right {border:1px solid #cccccc;}

jquery

$(document).ready(function() {
    var leftHeight = $('.left').height();
    $('.right').css({'height':leftHeight});
});

HTML

   <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
   </div>
   <div class="right">
    <p>Lorem ipsum dolor sit amet.</p>
   </div>

含める必要があります jquery

私はそれが長い間だったことを知っていますが、とにかく私の解決策を共有しています。これはjQueryのトリックです。

--- HTML

<div class="custom-column">
    <div class="column-left">
        asd
        asd<br/>
        asd<br/>
    </div>
    <div class="column-right">
        asd
    </div>
</div>

<div class="custom-column">
    <div class="column-left">
        asd
    </div>
    <div class="column-right">
        asd
        asd<br/>
        asd<br/>
    </div>
</div>

---- CSS

<style>
.custom-column { margin-bottom:10px; }
.custom-column:after { clear:both; content:""; display:block; width:100%; }
    .column-left { float:left; width:25%; background:#CCC; }
    .column-right { float:right; width:75%; background:#EEE; }
</style>

--- jQuery

<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $balancer = function() {
        $('.custom-column').each(function(){
            if($('.column-left',this).height()>$('.column-right',this).height()){
                $('.column-right',this).height($('.column-left',this).height())
            } else {
                $('.column-left',this).height($('.column-right',this).height())
            }

        });

    }
    $balancer();
    $(window).load($balancer());
    $(window).resize($balancer());

});
</script>

フィドル

HTML

<div class="container">

    <div class="left-column">

    </div>

    <div class="right-column">
        <h1>Hello Kitty!</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
    </div>

</div>

CSS

.container {
    float: left;
    width: 100%;
    background-color: black;
    position: relative;
    left: 0;
}

.container:before,
.container:after {
    content: " ";
    display: table;
}

.container:after {
    clear: both;
}

.left-column {
    float: left;
    width: 30%;
    height: 100%;
    position: absolute;
    background: wheat;
}

.right-column {
    float: right;
    width: 70%;
    position: relative;
    padding: 0;
    margin: 0;
    background: rebeccapurple;            
}

これは、同じ行のすべての要素の等しい高さを設定するjQueryプラグインです(要素のオフセットをチェックすることにより)。したがって、jQueryアレイに複数の行(異なるoffset.top)の要素が含まれている場合、各行はその列に最大高さの要素に基づいて分離された高さになります。

jQuery.fn.setEqualHeight = function(){

var $elements = [], max_height = [];

jQuery(this).css( 'min-height', 0 );

// GROUP ELEMENTS WHICH ARE ON THE SAME ROW
this.each(function(index, el){ 

    var offset_top = jQuery(el).offset().top;
    var el_height = jQuery(el).css('height');

    if( typeof $elements[offset_top] == "undefined" ){
        $elements[offset_top] = jQuery();
        max_height[offset_top] = 0;
    }

    $elements[offset_top] = $elements[offset_top].add( jQuery(el) );

    if( parseInt(el_height) > parseInt(max_height[offset_top]) )
        max_height[offset_top] = el_height;

});

// CHANGE ELEMENTS HEIGHT
for( var offset_top in $elements ){

    if( jQuery($elements[offset_top]).length > 1 )
        jQuery($elements[offset_top]).css( 'min-height', max_height[offset_top] );

}

};

    var numexcute = 0;
    var interval;
    $(document).bind('click', function () {

        interval = setInterval(function () {
            if (numexcute >= 20) {
                clearInterval(interval);
                numexcute = 0;
            }
            $('#leftpane').css('height', 'auto');
            $('#rightpane').css('height', 'auto');
            if ($('#leftpane').height() < $('#rightpane').height())
                $('#leftpane').height($('#rightpane').height());
            if ($('#leftpane').height() > $('#rightpane').height())

                $('#rightpane').height($('#leftpane').height());
            numexcute++;
        }, 10);

    });

私は同じ問題を抱えていたので、jQueryが最近のすべてのWebアプリケーションの一部であるため、jqueryを使用してこの小さな関数を作成しました。

function fEqualizeHeight(sSelector) {
    var sObjects = $(sSelector);

    var iCount = sObjects.length;

    var iHeights = [];

    if (iCount > 0) {
        $(sObjects).each(function () {
            var sHeight = $(this).css('height');
            var iHeight = parseInt(sHeight.replace(/px/i,''));
            iHeights.push(iHeight);
        });

        iHeights.sort(function (a, b) {
            return a - b
        });

        var iMaxHeight = iHeights.pop();

        $(sSelector).each(function () {
            $(this).css({
                'height': iMaxHeight + 'px'
            });
        });
    }
}

この関数をページ対応イベントで呼び出すことができます

$(document).ready(function(){
   fEqualizeHeight('.columns');
});

これがあなたのためにうまくいくことを願っています。

私は最近これに出会いましたが、ソリューションがあまり好きではなかったので、実験を試みました。

.mydivclass {inline-block; vertical-align: middle; width: 33%;}

<div>

<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>

</div>

<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!

</div>

</div>

私がここでやったことは、高さを最小高さに変えて、固定値を与えたことです。そのうちの1つがサイズ変更されている場合、もう1つは同じ高さのままになります。これがあなたが望むものであるかどうかはわかりません

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top