I have built a little sidebar with HTML and CSS that looks something like this:
<body>
<div class='sidebar'>
<div class='sidebar-buttons-section'>
<button class='sidebar-button' id='search'>
...
</button>
<button class='sidebar-button' id='account'>
...
</button>
<!-- and so on ... -->
</div>
</div>
</body>
I wanted the sidebar-button-section
to align to the center vertically, so I made a JavaScript function which does exactly that. I used this code to get the exact value for the top margin:
(document.documentElement.clientHeight - sideBarElement.offsetHeight) / 2;
I put that into a function called verticalAlign()
and then used two commands to ensure it's working properly:
verticalAlign();// call for the first time
window.onresize = verticalAlign; // align the sidebar
// everytime the window is resized
When I loaded the HTML something strange happened. The first thing I saw, was this: Sidebar when the page is loaded
The margin is too much and it's not perfectly aligned. When I resize the page however, this happens: Sidebar alignments when the page is resized
The buttons are all perfectly aligned as they should be. Why does the function not work properly when I call it for the first time?
Thanks in advance.