Как получить 2 деления одинаковой высоты, используя scroll-y и flexbox - PullRequest
1 голос
/ 26 марта 2020

Я хочу, чтобы этот прокручиваемый div был такой же высоты, как и div рядом с ним. Вот что я получил до сих пор:

<div style="display: flex">
    <div>
       The height must be determined by this div.
    </div>
    <div style="overflow-y: scroll">
       This div has a lot of content.
       The height must follow the div next to me.
    </div>
</div>

К сожалению, правильный div всегда такой же большой, как и его содержимое. Оба элемента имеют динамическое содержимое c, поэтому я не знаю точную высоту.

Ответы [ 2 ]

2 голосов
/ 26 марта 2020

Сначала прочитайте ее разницу между: overflow-y: scroll до auto (в вашем случае лучше использовать авто). https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

Еще один предварительный шаг align-items: flex-start; (Подобно этому высота столбца не будет совпадать).

.parent {
  display: flex;
  align-items: flex-start;
}

Как сделать отключить столбцы одинаковой высоты во Flexbox?

«реальное» решение (для всех случаев) - только на Javascript

/* set max-height by code */
var colHeight = document.getElementById("child_1").getBoundingClientRect().height;
console.log(colHeight);
document.getElementById("child_2").style.maxHeight = colHeight+"px";
.parent {
  display: flex;
}

#child_1{
  border: 3px solid orange;
}
#child_2 {
  overflow-y: auto;
  border: 2px solid violet;
}
<main class='parent'>
  <div id="child_1">
    <p>
      Fit to content in all cases - Fit to content in all cases  - Fit to content in all cases - Fit to content in all cases 
    </p>
    <p>
      Fit to content in all cases - Fit to content in all cases  - Fit to content in all cases - Fit to content in all cases 
    </p>
  </div>
  <div id="child_2">
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
  </div>
</main>

Дополнительный шаг (Установить максимальную высоту при изменении размера окна)

Когда вы устанавливаете max-height по коду - вы должны запустить это происходит каждый раз при изменении размера браузера (более безопасный подход для адаптивных сайтов): Как запустить функцию JavaScript при каждом изменении размера элемента HTML?

function resize() {
/* set max-height by code */
var colHeight = document.getElementById("child_1").getBoundingClientRect().height;
console.log(colHeight);
document.getElementById("child_2").style.maxHeight = colHeight+"px";
console.log('resized');
}

resize();
window.onresize = resize;
.parent {
  display: flex;
  align-items: flex-start;
}

#child_1{
  border: 3px solid orange;
}
#child_2 {
  overflow-y: auto;
  border: 2px solid violet;
}
<main class='parent'>
  <div id="child_1">
    <p>
      Fit to content in all cases - Fit to content in all cases  - Fit to content in all cases - Fit to content in all cases 
    </p>
    <p>
      Fit to content in all cases - Fit to content in all cases  - Fit to content in all cases - Fit to content in all cases 
    </p>
  </div>
  <div id="child_2">
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
  </div>
</main>

Дополнительное чтение:

Отключить на мобильном телефоне:

Этот трюк max-height не так полезно на маленьких экранах. Одно решение (если ширина окна больше, чем X, запустите функцию).

function resize() {
  /* set max-height by code */
  if (window.innerWidth > 960) {
    var colHeight = document.getElementById("child_1").getBoundingClientRect().height;
    console.log("window width" + window.innerWidth +"px");
    document.getElementById("child_2").style.maxHeight = colHeight+"px";
  }
}

resize();
window.onresize = resize;

Сделайте что-нибудь, если ширина экрана меньше 960 px


Почему CSS недостаточно?

Сохранить в помните, "максимальная высота" без какого-либо набора переполнения = "не отвечает" сайт.

Вариант 1 - левый столбец короче правого столбца:

Установите для высоты правого столбца значение: max-height: 100px;

.parent {
  display: flex;
}

#child_1{
  border: 1px solid lightgray;
}
#child_2 {
  overflow-y: scroll;
  max-height: 100px;
  border: 1px solid violet;
}
<main class='parent'>
  <div id="child_1">
    <p>
      Very short content
    </p>
  </div>
  <div id="child_2">
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
  </div>
</main>

Вариант 2 - левый столбец длиннее правого столбца:

В этом случае можно задать один из вариантов max-height для родителя (Очень Очень безответственный подход - потому что вы должны объявить переполнение для обоих столбцов) + Очень странный интерфейс:

.parent {
  display: flex;
  max-height: 100px;
}

#child_1{
  border: 3px solid orange;
  overflow-y: scroll;
}
#child_2 {
  overflow-y: scroll;
  border: 1px solid violet;
}
<main class='parent'>
  <div id="child_1">
    <p>
      Tall div
    </p>
    <p>
      Tall div
    </p>
    <p>
      Tall div
    </p>
    <p>
      Tall div
    </p>
    <p>
      Tall div
    </p>
  </div>
  <div id="child_2">
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
    <p>
      This div has a lot of content.
      The height must follow the div next to me.
    </p>
  </div>
</main>
1 голос
/ 26 марта 2020

Простым решением было бы добавить height или max-height к родительскому элементу. Таким образом, оба дочерних элемента имеют одинаковую высоту при любой ширине.

// HTML
<div id='container' class='parent'>
    <div id='content' class='child'>
       The height must be determined by this div.
    </div>
    <div class='child'>
       This div has a lot of content.
       The height must follow the div next to me.
    </div>
</div>
// CSS
.parent {
  display: flex;
  max-height: 70px; // remove if using JavaScript
}

.child {
  overflow: scroll;
}

В качестве альтернативы вы можете использовать JavaScript, чтобы определить текущую высоту вашего первого дочернего элемента и сделать ее высотой родительского элемента. .

ДОБАВЛЕНО:

// JS
const container = document.getElementById('container');
const content = document.getElementById('content');

const updateContainer = () => {
  let contentHeight = content.clientHeight + 'px';

  container.style.height = contentHeight;
}

updateContainer();

Это всего лишь пример. Вам нужно будет использовать прослушиватель событий для запуска функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...