Свернуть разделы по клику

У меня есть два раздела на моей странице, и я хочу свернуть/развернуть их вместе, когда пользователь нажимает на любой из них. Что происходит, так это то, что каждый раздел сворачивается/разворачивается отдельно. Как это решить?

.collapse-container {
  display: grid;
  grid-template-columns: 50% 50%;
}

.collapse-input:checked~p {
  height: auto;
}

.collapse {
  position: relative;
  margin: 0 auto;
  cursor: pointer;
}

.collapse-input {
  position: absolute;
  height: 100%;
  width: 100%;
  opacity: 0;
  cursor: pointer;
}

.collapse-content {
  transition: .2s ease-in;
  width: 100%;
  height: 0px;
}
<div className = "collapse-container">
  <section className = "collapse">
    <input className = "collapse-input" type = "checkbox" />
    <p className = "collapse-title">First Section</p>
    <p className = "collapse-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
  <section className = "collapse">
    <input className = "collapse-input" type = "checkbox" />
    <p className = "collapse-title">Second Section</p>
    <p className = "collapse-content">
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    </p>
  </section>
</div>

🤔 А знаете ли вы, что...
HTML поддерживает ссылки (гиперссылки) для перехода с одной страницы на другую.


1
54
2

Ответы:

Хотя вы установили высоту на 0, текст все еще отображается из-за переполнения. Итак, сначала добавьте overflow: hidden к тексту, чтобы скрыть его. Затем добавьте overflow: auto к проверенному тексту, чтобы показать его снова.

.collapse-container {
    display: grid;
    grid-template-columns: 50% 50%;
}
.collapse {
    position: relative;
    margin: 0 auto;
    cursor: pointer;
}
.collapse-input {
    position: absolute;
    height: 100%;
    width: 100%;
    opacity: 0;
    cursor: pointer;
}
.collapse-content {
    display: block;
    height: 0;
    overflow: hidden;   /*change here*/
    transition: .2s ease-in;
}
.collapse-input:checked~p{
    height: 20px;       /*use specific height instead of auto for transition*/
    overflow: auto;     /*change here*/
}
<div className = "collapse-container">
  <section class = "collapse">
    <input class = "collapse-input" type = "checkbox" />
    <p class = "collapse-title">First Section</p>
    <p class = "collapse-content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
  <section class = "collapse">
    <input class = "collapse-input" type = "checkbox" />
    <p class = "collapse-title">Second Section</p>
    <p class = "collapse-content">
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    </p>
  </section>
</div>

Решено

Обновлять

Опу нужны все <label>, чтобы иметь возможность контролировать весь контент. См. альтернативу и пример B.

Если вы используете невидимые флажки в качестве переключателей, вам следует добавить <label> и связать каждый из них с флажком с помощью значения атрибута for, совпадающего с атрибутом id флажка (см. рис. I). Как только связь между <input> и <label> установлена, любой щелчок по <label> автоматически связывается с ним <input>.

Сворачиваемый контент должен идти дальше <input> -- другие теги могут быть между ними, если они одинаковы для всех пар <input>/<label>. Рисунок II — это CSS для содержимого в скрытом состоянии. Если вы хотите, чтобы содержимое было видимым изначально, добавьте атрибут checked к <input>.

Рисунок I

<input id = "chk1" type = "checkbox" style = "display: none">
<label for = "chk1"><!-- [for = "ID of checkbox"] -->
  This is the part of the collapsible that is constantly
  visible and clickable
</label>  
<p>This is the collapsible content</p>

Рисунок II

p {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.65s ease-in-out;
}

Далее вам понадобится набор правил CSS, включающий проверяемый <input> и положение содержимого относительно <input>. Псевдокласс CSS :checked указывает, что стиль будет активен только тогда, когда установлен флажок/переключатель. Комбинатор соседнего элемента : + указывает элемент, который следует непосредственно за предыдущим элементом (см. рис. III).

Рисунок III

input:checked + label + p {
  max-height: 1000px;
}

Пример А

.switch {
  display: none;
}

.title {
  display: block;
  cursor: pointer;
}

.title:hover {
  color: red;
}

.content {
  max-height: 0;
  overflow: hidden;
  transition: max-height .25s ease;
}

.switch:checked+.title+.content {
  max-height: 300px;
}
<main>
  <section>
    <input id = "col1" class = "switch" type = "checkbox" />
    <label for = "col1" class = "title">First Section</label>
    <p class = "content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
  <section>
    <input id = "col2" class = "switch" type = "checkbox" />
    <label for = "col2" class = "title">Second Section</label>
    <p class = "content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
</main>

Альтернативный

Просто удалите все, кроме одного <input>. Переместите этот единственный <input> перед первым <section>. Затем измените атрибут for каждого <label> на id этого единственного <input>. См. Рисунок IV для CSS. ~ — это общий комбинатор родственных элементов

Рисунок IV

/* Change this */
.switch:checked+.title+.content {
  max-height: 300px;
}
/* to this */
.switch:checked~section .content {
  max-height: 300px;
}

Пример Б

.switch {
  display: none;
}

.title {
  display: block;
  cursor: pointer;
}

.title:hover {
  color: red;
}

.content {
  max-height: 0;
  overflow: hidden;
  transition: max-height .25s ease;
}

.switch:checked~section .content {
  max-height: 300px;
}
<main>
  <input id = "col" class = "switch" type = "checkbox" />
  <section>
    <label for = "col" class = "title">First Section</label>
    <p class = "content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
  <section>
    <label for = "col" class = "title">Second Section</label>
    <p class = "content">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </p>
  </section>
</main>