Using CSS, how can I show an element only when the parent content is overflowing?
(This is known as a "show more" button.)
Answer requirements:
- The content has a fixed
max-height
- The child content can contain any content (text, images, etc)
- The solution has to be CSS only.
CSS only is a very strict requirement. CSS only is faster, has no flicker on startup, is more responsive, etc.
Non-working Code
.container {
max-height: 100px;
overflow: hidden;
position: relative;
margin: 1rem;
}
.big-content {
background: linear-gradient(to bottom, black, white);
height: 200px;
}
.small-content {
background: linear-gradient(to bottom, black, white);
height: 50px;
}
.overflow-message {
position: absolute;
bottom: 0px;
}
<div class="container">
<div class="big-content"></div>
<div class="overflow-message">Overflowing (visible)</div>
</div>
<div class="container">
<div class="small-content"></div>
<div class="overflow-message">Not overflowing (not visible)</div>
</div>
Research
No similar question is CCS-only.
2
Answers
Yes, we can use CSS
max-height
andcalc
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.
calc(MAX-HEIGHT - 100%)
calc
and-
calc((MAX-HEIGHT - 100%) * 10000)
position: absolute; bottom: calc((MAX-HEIGHT - 100%) * 10000);
Overflowing Example
Putting it together, gives us
bottom: calc((100% - 100px) * 10000);
, for a container which has amax-height: 100px
.The linear gradient is overflowing, which can be seen as it cuts off before it finishes the gradient.
Non-overflowing Example
The linear gradient does not cut off, so the text is not visible.
Adding a solution for the future using scroll-driven animations where you don’t need to know the value of
max-height
orheight
.You can test it using the latest version of chrome