One solution is to use the function calc()
in the max-height
(then you don’t need the bottom
and of height
).
Just subtract the 100vh
(height of the viewport) by 20px
(distance from the top
+ desired distance from the bottom
):
max-height: calc(100vh - 20px);
If there is some other property of spacing in the element, such as padding-top
or padding-bottom
, these values must be added to the 20px
. For example, if the widget has a padding: 20px
, would be:
max-height: calc(100vh - 60px);
That is, the 20px
normal + 20px
of padding-top
+ 20px
of padding-bottom
, totalling 60px
.
See an example without the padding
:
ul {
margin: 0;
position: fixed;
right: 10px;
top: 10px;
width: 70%;
background-color: red;
max-height: calc(100vh - 20px);
overflow: auto;
}
<ul>
<li>
<a href="#">Test</a>
</li>
<li>
<a href="#">Test2</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test10</a>
</li>
</ul>
Now an example with padding
:
ul {
margin: 0;
position: fixed;
right: 10px;
top: 10px;
width: 70%;
background-color: red;
max-height: calc(100vh - 60px);
overflow: auto;
padding: 20px;
}
<ul>
<li>
<a href="#">Test</a>
</li>
<li>
<a href="#">Test2</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test3</a>
</li>
<li>
<a href="#">Test10</a>
</li>
</ul>
Guy if the element is at 10px from the top of the page and 10px from the bottom logically it will take up all the space feel from that range
– hugocsl
@hugocsl, I get it, that way then it won’t work. But you get the idea? There would be some way to make it work without having to add another parent div (I thought I’d go around like this)?
– Diego Vieira
@Sam, I ended up solving with JS even. I couldn’t find another way with CSS.
– Diego Vieira
I think with jQuery it would be easier
– Sam