I am implementing an accordion with just HTML and CSS. I use an hidden checkbox and the :checked
state to trigger the collapsible inner part of the accordion.
The header part has a text label and a checkbox that will be customized with an icon, therefore I wrapped these elements in a Flex parent to align them. The issue I am facing is that I need to build a condition that targets the COLLAPSIBLE
div, sibling of the HEADER
, when the checkbox (header's child) is checked.
My Template:
<div class="accordion-container rounded">
<div class="accordion-header flex-center-y">
<!-- I would style the checkbox to have a custom icon as content -->
<input id="accordion1" class="accordion-toggle" type="checkbox" />
<label for="accordion1" class="lbl-toggle">
<strong>Header label</strong>
</label>
</div>
<div class="accordion-collapsible"> <!-- This is the part that should expand when checkbox is checked -->
<div class="accordion-inner-content">
<p class="accordion-inner-text">
Inside an accordion content...
</p>
</div>
</div>
</div>
SCSS
.accordion-container {
padding: 2.15em;
border: 1px solid black;
.accordion-header {
.accordion-toggle {
// In a second version the checkbox with the icon will be visible.
// In this version it is not displayed (only the label is visible in this case)
display: none;
}
}
.accordion-collapsible {
max-height: 0px;
overflow: hidden;
transition: max-height 0.25s ease-in-out;
}
// I would need something similar to the rule below:
// set max-height to accordion-collapsible if the child of accordion-header is checked
(.accordion-header > .accordion-toggle:checked) + .accordion-collapsible {
max-height: 100vh;
}
}
If I remove the .accordion-header
div and I keep the checkbox
and the .accordion-collapsible
div as sibling, the logic works with the following rule, but I would lose the possibility to align the elements in the header (other elements, like buttons, might potentially be added after the label):
.accordion-toggle:checked + .accordion-collapsible {
max-height: 100vh;
}
Is there a way to expand the .accordion-collapsible
div, when the checkbox is clicked?
If possible I would keep the header as it allows me to nicely align its content.