Сворачиваемая высота текста в чистом css

Вот фрагмент того, что у меня есть до сих пор:

#expand {
  height: 0px;
  width: 0px;
  overflow: hidden;
  transition: height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}


/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}
<main>
  <input id = "toggle" type = "checkbox" />
  <label for = "toggle">Hidden Kitten</label>
  <div id = "expand">
    <section>
      <p>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.</p>
    </section>
  </div>

  <input id = "toggle1" type = "checkbox" />
  <label for = "toggle1">Hidden Kitten</label>
  <div id = "expand">
    <section>
      <p>mew</p>
    </section>
  </div>
</main>

Вы можете видеть в селекторе input:checked + label + #expand, ширина и высота фиксированы.

Я могу установить ширину в процентах, но если я попытаюсь установить высоту в процентах, это испортит анимацию. Как это исправить? Я не знаю высоту текста заранее. Я хотел бы использовать только CSS для этого.

Вы не можете анимировать высоту до auto.

Paulie_D 30.05.2019 18:04

@cale_b этот ответ был именно тем, что мне было нужно, спасибо! я все равно отмечу ответ Quantastical как правильный, так как он опубликовал его первым.

Zee 30.05.2019 18: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 страниц, которые помогут...
0
2
274
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

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

Вы можете попробовать использовать max-height вместо height.

#expand {
  max-height: 0px;
  width: 0px;
  overflow: hidden;
  transition: max-height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  max-height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}


/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}
<main>
  <input id = "toggle" type = "checkbox" />
  <label for = "toggle">Hidden Kitten</label>
  <div id = "expand">
    <section>
      <p>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.</p>
    </section>
  </div>

  <input id = "toggle1" type = "checkbox" />
  <label for = "toggle1">Hidden Kitten</label>
  <div id = "expand">
    <section>
      <p>mew</p>
    </section>
  </div>
</main>

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

Ввод со смещающимся полем метки (во всех CSS) без необходимости
Как создать нокаутирующий текст на фоновом изображении, чтобы текст мог анимироваться поверх изображения
Как применить свойство css border-radius в ion-menu в ionic 4?
Можно ли остановить (бесконечную) анимацию ключевых кадров CSS в определенный момент времени или определенный ключевой кадр?
Изображение src прерывается, когда оно находится на другой странице, отличной от домашней
Как построить и управлять цветом 4 квадратов?
Укладывать полноразмерные фоновые изображения с помощью бутстрапа по горизонтали?
Как взаимодействовать с элементами внутри #shadow-root (open) при очистке данных браузера Chrome с помощью cssSelector
Сообщение об ошибке пользовательского валидатора response-bootstrap-table2 отображается в пользовательском интерфейсе
При наведении курсора на предложение поля Chrome ввод уменьшается