Yes, we can use CSS max-height
and calc
which have been supported in Chrome since 2013.
The idea is that we can push the "show more" button down if there is remaining space, but leave it unchanged if there is no remaining space.
calc(MAX-HEIGHT - 100%)
calc
and -
calc((MAX-HEIGHT - 100%) * 10000)
position: absolute; bottom: calc((MAX-HEIGHT - 100%) * 10000);
We can use CSS to make a button which toggles behavior. This can be done by taking advantage of the :checked
css selector, and the sibling selector +
.
The checkbox must exist before the content it controls, we have to a label with for
to toggle it. for
allow clicking on the label to also click on the checkbox.
#expand-toggle:checked + .ShowMoreContainer {
max-height: none;
}
Using contenteditable
you can remove text to dynamically reduce the size of the content, and see that the "Show More" button will hide as soon as the content stops overflowing.
Unfortunately, contenteditable
also results in scrolling the parent if you move the cursor down. Similar issues happen if hidden content is focused. I only know how to solve this issue with JavaScript so I left it as is.
.ShowMoreContainer {
max-height: 100px;
}
#expand-toggle:checked + .ShowMoreContainer {
max-height: none;
}
#expand-toggle:checked + div .show-more {
display: none;
}
#expand-toggle:not(:checked) + div .show-less {
display: none;
}
<input type="checkbox" id="expand-toggle" style="display: none" />
<div
class="ShowMoreContainer"
style="overflow: hidden; position: relative; border: 1px solid black; box-sizing: content-box"
>
<div contenteditable>1<br/>2<br/>3<br/>4<br/>5<br/>6</div>
<div class="show-more" style="position: absolute; bottom: calc((100% - 100px) * 10000)">
<label for="expand-toggle">
<div style="background: white; cursor: pointer;">Show More ...</div>
</label>
</div>
<div class="show-less">
<label for="expand-toggle">
<div style="background: white; cursor: pointer;">Show Less ...</div>
</label>
</div>
</div>