Getting height of an element and setting CSS

So, I want to get the height of the container and then use that to set the margin of another element. Now, I’m not asking anyone to do this, but rather help me know if I’m following the right steps. I’m very new to javascript and jQuery

1)Create a variable to store the height info

2)Get the height of the element by ID when the document loads

3)Convert the height of the variable to a string an add em’s

4)Set the OTHER element’s class of the element equal to the string

5)Add the css to the element



You don’t need to do this in two steps:

var myElementHeight = // code to get element height here

Also, if you put your JS at the bottom of your page, directly before the closing </body> tags, then the page will be loaded by default, so you don’t need to wait for it.

The height will be returned in px. Therefore adding ems might cause unexpected results.

I don’t understand this.

Apart from the fact that Margin may not be capitalized (I think) and the fact that you are not using the height information you obtained from the first container, this seems reasonable.

I would do it something like:

var myElementHeight = $(selector).cdeToGetHeight
$(secondElementSelector).css("margin-top", myElementHeight);

I think that should work.

By the way, I find it great that you’re not simply asking for the answer, but trying to understand what is going on.
Feel free to let me know if you need any more guidance with this.

Thanks. After being stumped for a while I got your method to work. I didn’t know that you could put the variable name after, “margin-top”. Definitely still learning jQuery syntax.

<script type=“text/javascript”>

$(document).ready(function() {

var ElementHeight = $( “#MainHead” ).height();


However, I could only get it to work locally. I tried in on the dev site, but it won’t work. Locally, if I resized the browser window and reloaded then the flag would get pushed right below the header. This is exactly what I need. I did this because I was having to do too many media queries for the flag to sit right below the header. So, any ideas on why I can’t get this to work online??? thx

I guess this might be a bad idea if someone turns their phone or tablet though, huh?


If you look at the console on the site you link to, you see:

Uncaught ReferenceError: $ is not defined

How do I do this?

This usually means that you haven’t included jQuery.

I am always weary of altering a page’s layout using JavaScript.

Can you not use media queries instead?