Как я могу сохранить количество элементов (динамическое) от разрушения внутри столбцов CSS?
Там в column-count
, но мне интересно, есть ли такая вещь, как "количество элементов" для элементов внутри столбца CSS? У меня возникают проблемы при попытке зафиксировать количество элементов в 3 часто задаваемых вопросах по столбцам без указания высоты для самого столбца.
В этом примере я хотел бы, чтобы в каждом столбце было 3 элемента, независимо от того, насколько длинным является вопрос или ответ в каждом элементе. На настоящем сайте я не буду знать точное количество элементов, поэтому я просто хотел бы сохранить их "сбалансированными".
Вы можете видеть, что я пытался использовать flexbox, но панель ответов будет содержать динамическое содержимое (то же самое относится и к количеству вопросов / элементов). Моя цель - сделать так, чтобы он выглядел как макет каменной кладки всякий раз, когда отображаются или отображаются панели ответов.
.m-faqs {
/*display: flex;
flex-flow: row wrap;
justify-content: space-between;*/
column-count: 3;
column-gap: 50px;
}
.m-faqs_item {
margin-bottom: 20px;
position: relative;
/*flex: 0 0 47%;
align-self: baseline;*/
display: inline-block;
break-inside: avoid;
width: 100%;
}
.m-faqs_title {
margin-top: 0;
margin-bottom: 0;
}
.m-faqs_question {}
.m-faqs_question-link {
display: inline-block;
}
.m-faqs_answer {}
.m-faqs_item.active .m-faqs_answer {
display: block;
}
<div class="m-faqs">
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<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>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
</div>
2 ответа
Когда используешь column-count
, доступное пространство распределяется для заданного количества текста, а не для заданного количества элементов. Когда контейнер не имеет заданной высоты, текст будет распределен равномерно, поэтому, если более длинный вопрос занимает больше места, в следующем столбце это пространство может быть выделено для двух вопросов, как мы видим в вашем примере.
Есть несколько обходных путей:
Самый простой и эффективный способ - визуализировать HTML, элементы которого разделены на 3 контейнера, или использовать код JS, который будет считать все элементы и упаковывать их в контейнеры. Каждый контейнер будет тогда столбцом, который будет вести себя точно так, как вы описали.
Используйте сетку. Недостатком является то, что он не имеет большого охвата браузера, и выглядит не так, как вы, вероятно, ожидаете:
.m-faqs {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-column-gap: 50px;
}
.m-faqs_item {
margin-bottom: 20px;
}
<div class="m-faqs">
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<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>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
</div>
- Та же проблема с отображением относится к решению flex, за исключением того, что flexbox имеет лучшее покрытие и может безопасно использоваться для всех браузеров.
.m-faqs {
display: flex;
flex-wrap: wrap;
}
.m-faqs_item {
width: calc((100% - 150px)/3);
}
.m-faqs_item:nth-of-type(3n), .m-faqs_item:nth-of-type(3n + 2) {
margin-left: 50px;
}
<div class="m-faqs">
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<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>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
<div class="m-faqs_item">
<h3 class="m-faqs_title"><span class="m-faqs_question">Question here</span></h3>
<div class="m-faqs_answer">
<p>Here's the answer.</p>
</div>
</div>
</div>
Кроме этого, я не думаю, что есть какие-либо удовлетворительные решения CSS.
Если в вашем контейнере есть
column-count: *numeric*
Установите ваши предметы внутри контейнера в
break-inside:avoid
Для обратной совместимости
page-break-inside:avoid;
-moz-column-break-inside:avoid;
break-inside:avoid