Jak utrzymać dwie div-by-side na tej samej wysokości?

Mam dwie div obok siebie. Chciałbym, aby ich wysokość była taka sama i pozostała taka sama, jeśli jeden z nich zmieni rozmiar. Nie mogę tego rozgryźć. Pomysły?

Aby wyjaśnić moje mylące pytanie, chciałbym, aby oba pola były zawsze tego samego rozmiaru, więc jeśli jedno rośnie, ponieważ tekst jest w nim umieszczony, drugie powinno rosnąć, aby dopasować wysokość.

<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>
Author: ndmeiri, 2010-06-08

20 answers

Flexbox

Z flexbox jest to pojedyncza deklaracja:

.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>
W starszych przeglądarkach mogą być wymagane prefiksy, patrz obsługa przeglądarki.
 460
Author: Pavlo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-19 12:09:45

Jest to częsty problem, który wielu napotkało, ale na szczęście niektóre inteligentne umysły, takie jak Ed Eliot na swoim blogu opublikowały swoje rozwiązania w Internecie.

Zasadniczo to, co robisz, to sprawiasz, że oba divy / kolumny są bardzo wysokie, dodając padding-bottom: 100%, a następnie "oszukujesz przeglądarkę", aby myślała, że nie są tak wysokie, używając margin-bottom: -100%. Lepiej to wyjaśnia Ed Eliot na swoim blogu, który również zawiera wiele przykładów.

.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>
 137
Author: lambda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-14 13:44:58

Jest to obszar, w którym CSS nigdy nie miał żadnych rozwiązań - musisz używać znaczników <table> (lub udawać je za pomocą wartości CSS display:table*), ponieważ jest to jedyne miejsce, w którym zaimplementowano "zachowaj kilka elementów o tej samej wysokości".

<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>

Działa to we wszystkich wersjach Firefoksa, Chrome i Safari, Operze od co najmniej wersji 8, A W IE od wersji 8.

 54
Author: Paul D. Waite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-23 15:01:38

Using Javascript

Używając jQuery możesz to zrobić w super prostym skrypcie jednoliniowym.

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

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

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

Using CSS

To jest trochę bardziej interesujące. Technika ta nazywana jest Faux Columns . Mniej więcej nie ustawiasz rzeczywistej wysokości na taką samą, ale ustawiasz niektóre elementy graficzne tak, aby wyglądały na tej samej wysokości.
 34
Author: Derek Adair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-30 12:56:49

Dziwię się, że nikt nie wspomniał o (bardzo starej, ale wiarygodnej) technice kolumn absolutnych: http://24ways.org/2008/absolute-columns/

Moim zdaniem jest znacznie lepszy od obu Faux kolumn i jednej prawdziwej techniki layoutu.

Ogólna idea jest taka, że element z position: absolute; będzie ustawiony względem najbliższego elementu nadrzędnego, który ma position: relative;. Następnie rozciągasz kolumnę, aby wypełnić 100% wysokości, przypisując zarówno top: 0px;, jak i bottom: 0px; (lub dowolne piksele / procenty właściwie to potrzebuję.) Oto przykład:

<!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>
 12
Author: geofflee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-06 02:21:06

Możesz użyć jQuery ' s Equal Heights Plugin do osiągnięcia, ta wtyczka sprawia, że wszystkie div dokładnie tej samej wysokości co inne. Jeśli jeden z nich rośnie, a drugi również będzie rosnąć.

Tutaj przykład realizacji

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.

Oto link

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

 11
Author: Starx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-08 14:03:25

Możesz użyć Faux Columns .

Zasadniczo wykorzystuje obraz tła w Div zawierającym symulację dwóch Div o równej wysokości. Ta technika umożliwia również dodawanie cieni, zaokrąglonych narożników, niestandardowych obramowań lub innych ciekawych wzorów do kontenerów.

Działa tylko z polami o stałej szerokości.

Dobrze przetestowane i poprawnie działające w każdej przeglądarce.

 8
Author: Arve Systad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-07 12:14:38

Właśnie zauważyłem ten wątek podczas poszukiwania tej samej odpowiedzi. Właśnie zrobiłem małą funkcję jQuery, mam nadzieję, że to pomoże, działa jak urok:

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>
 4
Author: Mike Wells,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-05 15:34:53

To pytanie zadano 6 lat temu, ale nadal warto udzielić prostej odpowiedzi za pomocąflexbox layout.

Po prostu dodaj następujący CSS do ojca <div>, to zadziała.

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

Pierwsze dwie linie deklarują, że zostanie wyświetlona jako flexbox. I flex-direction: row mówi przeglądarkom, że ich dzieci będą wyświetlane w kolumnach. I align-items: stretch spełni wymóg, aby wszystkie elementy dziecięce rozciągały się na taką samą wysokość, że jeden z nich stał się wyższy.

 3
Author: Hegwin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-17 08:34:59

Jeśli nie masz nic przeciwko temu, aby jeden z divbył mistrzem i dyktował wysokość dla obu divjest to:

Fiddle

Bez względu na wszystko, div po prawej stronie rozszerzy się lub zgnieci i przepełni, aby dopasować wysokość div po lewej.

Oba divmuszą być bezpośrednimi potomkami kontenera i muszą określać w nim swoje szerokości.

Odpowiedni 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;
}
 2
Author: Hashbrown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-23 06:27:32

Lubię używać pseudo elements, aby to osiągnąć. Możesz użyć go jako tła treści i pozwolić im wypełnić przestrzeń.

Dzięki temu można ustawić marginesy między kolumnami, obramowaniami itp.

.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>
 2
Author: Adrian Menendez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-15 10:40:21

Sposób siatki CSS

Nowoczesnym sposobem na zrobienie tego (który również pozwala uniknąć konieczności deklarowania <div class="row"></div> - owijarki wokół dwóch elementów) byłoby użycie siatki CSS. Daje to również łatwą kontrolę nad przerwami między wierszami/kolumnami artykułów.

.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>
 1
Author: connexo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 14:29:29

Możesz użyć jQuery, aby to łatwo osiągnąć.

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>

Musisz dołączyć jQuery

 0
Author: pixeltocode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-08 14:14:03

The Fiddle

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;            
}
 0
Author: drjorgepolanco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-30 15:18:26

Wiem, że minęło dużo czasu, ale i tak dzielę się moim rozwiązaniem. To jest sztuczka 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>
 -1
Author: Roy Vincent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-17 13:47:43

Jest to wtyczka jQuery, która ustawia jednakową wysokość dla wszystkich elementów w tym samym wierszu(sprawdzając przesunięcie elementu.top). Więc jeśli Twoja tablica jQuery zawiera elementy z więcej niż jednego wiersza(inne przesunięcie.top), każdy wiersz będzie miał oddzielną wysokość, opartą na elemencie o maksymalnej wysokości w tym wierszu.

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] );

}

};

 -1
Author: Déján Kőŕdić,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-31 07:55:41
    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);

    });
 -2
Author: tcao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-05 22:05:26

Miałem ten sam problem, więc stworzyłem tę małą funkcję używając jquery, ponieważ jquery jest obecnie częścią każdej aplikacji internetowej.

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'
            });
        });
    }
}

Możesz wywołać tę funkcję w zdarzeniu page ready

$(document).ready(function(){
   fEqualizeHeight('.columns');
});
Mam nadzieję, że to ci pomoże.
 -2
Author: Master Programmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-21 16:18:09

Ostatnio natknąłem się na to i nie bardzo podobały mi się rozwiązania, więc próbowałem eksperymentować.

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

 -3
Author: tushar747,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 03:19:08
<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>

To, co zrobiłem tutaj, to zmiana wysokości na min-height i nadanie jej stałej wartości. jeśli jeden z nich jest coraz większy, drugi pozostanie tej samej wysokości. Nie wiem, czy to jest to, czego chcesz

 -4
Author: Wai Wong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-08 13:53:35