Working on a project requiring old-school CSS support and want to keep <aside>
filling up the page by remaining the same height as the <article>
element’s box (It may be between a header and footer, in which case it would not extend past them.)
<article id="article"> ... <aside id="sidebar">
Here’s my attempt at dynamically setting the height. It doesn’t seem to work.
<script> function sidebarHeight() { sidebar=window.document.getElementById('sidebar') article=window.document.getElementById('article') sidebar.style.height=article.style.height; console.log('article.style.height: ' + article.style.height); } window.onresize=sidebarHeight; </script>
This doesn’t work because article.style.height
always has the value ""
instead of the current height. How can I keep the sidebar stretched vertically in sync with the article height?
By the way, can someone explain why the only way to get at properties like height, or at least color, which I know works, requires a call to getElementById()
? If I use the more logical-sounding getElementsByTagName('article')
I get access to a much more limited set of properties.
Advertisement
Answer
To get the calculated height onresize
you need to use .offsetHeight
and you need to add a unit to the returned value.
sidebar.style.height = `${article.offsetHeight}px`;
also, your DOM queries should just be called on document
sidebar = document.getElementById('sidebar') article = document.getElementById('article')
article { float: left; height: 40vh; width: 75vw; background-color: gray; } aside { float: right; width: 20vw; background-color: tomato; }
<article id="article"></article> <aside id="sidebar"></aside> <script> function sidebarHeight() { sidebar= document.getElementById('sidebar') article= document.getElementById('article') sidebar.style.height= `${article.offsetHeight}px`; } window.onresize=sidebarHeight; </script>