Содержимое Flex не соответствует высоте родительского содержимого

У меня есть следующий макет, это оболочка (контент), которая содержит некоторые другие div, которые также имеют некоторые свойства flex.

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

.content {
  width: 100%;
  height: 400px;
  display: flex;
  overflow: auto;
  background-color: blue;
}

.a {
  width: 165px;
  height: 100%;
  flex-grow: 1;
  background-color: red;
}

.b {
  width: 65px;
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  justify-content: center;
  background-color: yellow;
  height: 100%;
}

.c {
  width: 165px;
  flex-grow: 1;
  margin-right: 15px;
  background-color: green;
  height: 100%;
}
<div class = "content">
  <div class = "a">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
    a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
  <div class = "b">
    <div class = "separator">
      s
    </div>
  </div>
  <div class = "c">
    c
  </div>
</div>

Чего я хотел бы достичь: - красные, желтые, зеленые элементы должны иметь такую ​​же высоту, как и синий (контент), поэтому при прокрутке вы не видите синюю часть внизу

Как этого добиться? Что не так с моим кодом?

Я поддерживаю только последнюю версию Chrome и могу использовать CSS3.

Удалите overflow: auto в контейнере и добавьте box-sizing: border-box в класс .b, чтобы ваш отступ не приводил к переполнению контейнера. Проверьте это, codepen.io/Tan007/pen/joMqYM

Tan-007 13.05.2019 09:25
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
2
2
477
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Ответ принят как подходящий

Ваш .a переполняется .content, поэтому внизу отображается синяя секция.

Предоставляя .a или, скорее, всем дочерним элементам div автоматическое переполнение, они будут следовать росту своего родителя и избегать переполнения содержимого.

Тем не менее, он представит полосу прокрутки. Если вам удобно скрывать переполненный текст, вы можете вместо этого использовать overflow: hidden.

.content {
  width: 100%;
  height: 400px;
  display: flex;
  overflow: auto;
  background-color: blue;
}

.content > div {
  overflow: auto;
}

.a {
  width: 165px;
  height: 100%;
  flex-grow: 1;
  background-color: red;
}

.b {
  width: 65px;
  padding-top: 20px;
  padding-bottom: 20px;
  background-color: yellow;
}

.c {
  width: 165px;
  margin-right: 15px;
  flex-grow: 1;
  background-color: green;
  height: 100%;
}
<div class = "content">
  <div class = "a">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
    a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
  <div class = "b">
    <div class = "separator">
      s
    </div>
  </div>
  <div class = "c">
    c
  </div>
</div>

Вы могли бы попробовать:

flex: 1 1 auto

Его размеры основаны на свойствах ширины/высоты.

проверить Css Tricks статья об этом.

РЕДАКТИРОВАТЬ

Удалите flex-grow: 1 и это будет нужная вам высота.

.content {


width: 100%;
  height: 400px;
  overflow: auto;
  background-color: blue;
}

.inner{
  display: flex;
}

.a {
  width: 165px;
  background-color: red;
}

.b {
  width: 65px;
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  justify-content: center;
  background-color: yellow;
}

.c {
  width: 165px;
  margin-right: 15px;
  background-color: green;
}

где мне его разместить? не могли бы вы привести мне пример?

Radex 13.05.2019 09:33

Я открыл ваш пример в хроме и использовал консоль разработчика, чтобы удалить CSS flex-grow, а высота отрегулирована до полной высоты родителя.

Grant Miles 13.05.2019 10:03

Я думаю, что лучший вариант для вашей проблемы либо

  • переход overflow: auto; из класса .content в его детей.
  • измените height: 400px; на min-height: 400px;, если у вас нет проблем с размером контейнера более 400 пикселей;
  • добавление обертки div с height: 400px; и overflow: auto; вокруг .content и удаление обоих правил из .content (имо лучший вариант)

Удалите display: flex из .content и height: 100% из .a .b .c, а затем оберните ваши элементы в div и придайте ему гибкость отображения.

Рабочий код:

.content {
  width: 100%;
  height: 400px;
  overflow: auto;
  background-color: blue;
}

.inner{
  display: flex;
}

.a {
  width: 165px;
  flex-grow: 1;
  background-color: red;
}

.b {
  width: 65px;
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  justify-content: center;
  background-color: yellow;
}

.c {
  width: 165px;
  flex-grow: 1;
  margin-right: 15px;
  background-color: green;
}
<div class = "content">
<div class = "inner">
  <div class = "a">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
    a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
  <div class = "b">
    <div class = "separator">
      s
    </div>
  </div>
  <div class = "c">
    c
  </div>
</div>
  
</div>

Проблема здесь в переполнении раздела. Когда вы привязываете высоту .content 400px. Таким образом, есть два способа: вы можете либо освободиться от них, чтобы привязать высоту, либо использовать прокрутку переполнения для раздела .a. Вы можете сравнить предыдущий и фиксированный код ниже.

.content {
  width: 100%;
  /*height: 400px;*/
  display: flex;
  overflow: auto;
  background-color: blue;
}

.a {
  width: 165px;
  /*height: 100%;*/
  flex-grow: 1;
  background-color: red;
}

.b {
  width: 65px;
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  justify-content: center;
  background-color: yellow;
  /*height: 100%;*/
  box-sizing: border-box;
}

.c {
  width: 165px;
  flex-grow: 1;
  margin-right: 15px;
  background-color: green;
  /*height: 100%;*/
}
<div class = "content">
  <div class = "a">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
    a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
  <div class = "b">
    <div class = "separator">
      s
    </div>
  </div>
  <div class = "c">
    c
  </div>
</div>

.content {
  width: 100%;
  height: 400px;
  display: flex;
  overflow: auto;
  background-color: blue;
}

.a {
  width: 165px;
  height: 100%;
  flex-grow: 1;
  background-color: red;
}

.b {
  width: 65px;
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  justify-content: center;
  background-color: yellow;
  height: 100%;
}

.c {
  width: 165px;
  flex-grow: 1;
  margin-right: 15px;
  background-color: green;
  height: 100%;
}
<div class = "content">
  <div class = "a">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took
    a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
  <div class = "b">
    <div class = "separator">
      s
    </div>
  </div>
  <div class = "c">
    c
  </div>
</div>

Другие вопросы по теме