79238505

Date: 2024-11-29 22:41:30
Score: 2
Natty:
Report link

Yes, we can use CSS max-height and calc which have been supported in Chrome since 2013.

Hide If Overflowing

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.

  1. calc(MAX-HEIGHT - 100%)
    • Calculate the remaing space using calc and -
  2. calc((MAX-HEIGHT - 100%) * 10000)
    • Multiply by a large number, so 1px remaining results in an a large offset. This prevents the button from being partially visible.
  3. position: absolute; bottom: calc((MAX-HEIGHT - 100%) * 10000);
    • Offset the button from the bottom.
    • If there is any remaining space, bottom will be set to a large negative value, resulting in the button being hidden.

CSS Based Button

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;
}

Code Example

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>

Reasons:
  • Blacklisted phrase (1): how to solve
  • RegEx Blacklisted phrase (1): Similar issue
  • RegEx Blacklisted phrase (2): know how to solve
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • High reputation (-1):
Posted by: yeerk