Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Calc: Wrong values when using percentage?

Tags:

html

css

I have a problem with CSS calc returning wrong values for %.

My idea was to create a sticky sidebar where you first scroll to the end and then it stays there until end of content. It works with vh units and when I use absolute height for the div, but not when I use %.

.sidebar {
position: sticky;
top: calc(100vh - 100%); <-- does not work
top: calc(100vh - 1600px); <-- works as expected.
}

So maybe I misunderstood what % means in this context (my understanding: height of the object to which the class .sidebar is applied) or is calc() just not good to use?

edit: enter image description here Here is, what I intended (yellow: viewport; sidebar: blue; red: content). Sidebar is scrolled until the bottom edge of it and viewport are on the same height, then only content is moving and after that bottom lines of sidebar and content are on the same level. It actually works with fixed values.

It seems like the answer is not that parents height is used, because that would result in a greater value, leading to a sidebar-bottom-line HIGHER than the viewport-bottom, but it is actually lower.

Thanks and have a nice day!

like image 284
Lucas J. Lischka Avatar asked Oct 17 '22 17:10

Lucas J. Lischka


1 Answers

The % is the percentage of the size of the element it is contained in. So if your page is very long it maybe be well over the size of the viewport, so 100vh - 100% will go negative. This means the sidebar will extend over the top of your viewport. If your intention is to put the sidebar fixed to the top of the page you may as well just put

top: 0
like image 59
cirkel Avatar answered Oct 20 '22 19:10

cirkel