Scott Eldo Scott Eldo - 3 months ago 12
CSS Question

Set an elements margin to dynamically stay same as another elements height jQuery

I would like to set the margin-bottom of an element to always match the value of a different elements height.

So if #footer current height is 310px I would like the margin-bottom of .content-wrap to also be 310px and them to tay the same regardless of #footer height. I have the below code but its not having any effect on the margin at all currently... I've not used jQuery to store and output values/css before as you can tell!

$(function () {
updateDivsMargins();
$(window).resize(updateDivsMargins);

function updateDivsMargins() {
$('.content-wrap').each(function () {
$(this).css({
'margin-bottom': $("#footer").height();,
});
});
}
});

Answer

You have a syntax error at 'margin-bottom': $("#footer").height();,

Remove the semicolon ; and it works as expected.

Here's the working snippet:

 $(function() {
   updateDivsMargins();
   $(window).resize(updateDivsMargins);

   function updateDivsMargins() {
     $('.content-wrap').each(function() {
       $(this).css({
         'margin-bottom': $("#footer").height(),
       });
     });
   }
 });
#footer {
  position: absolute;
  width: 100%;
  height: 20%;
  background: tomato;
}

.content-wrap {
  background: lavender;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci dignissimos, qui corporis ipsum obcaecati mollitia praesentium consequuntur architecto sint illum facilis voluptas, maxime repellat molestiae quis. Labore, quibusdam consequuntur ab.</div>
<hr>
<div class="content-wrap">
  Content wrap lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab ut aperiam consequuntur hic aliquid perferendis quo eligendi rem, sint ea, officia totam. Sequi enim, quaerat. Assumenda, nulla atque tempora totam.
</div>
<div id="footer"></div>

And here's the JSFiddle full screen preview.