user2498890
user2498890

Reputation: 1556

Use javascript to calculate div height as a percentage?

After some searching I've come across code similar to the demo below that uses js to calculate the height of a div and then sets that number as a margin top to the div below.

This works fine however I need it to calculate as a percentage rather than a 'px' as when I scale down and the responsive image gets smaller the margin-top obviously doesn't scale with it. I'm not sure if this is possible or how I would achieve it?

jsFiddle

JS:

$(document).ready( function(){
  var fixedHeight = $(".fixed-container").outerHeight(true);
  $(".scrolling-container").css({"float":"left", "margin-top":
  fixedHeight + "px"});
});

Any suggestions or solutions would be most appreciated.

Upvotes: 0

Views: 1760

Answers (3)

ntgCleaner
ntgCleaner

Reputation: 5985

You don't need a percentage if you're using jQuery. Use $(window).resize() to update it any time the window updates.

The other reason you can't use a percentage on the height is that you have no container that has a set height. This means it's going to be a percentage of the entire page. The more content you add, the bigger the margin will be. Use this code to achieve what you're doing:

function extraMargin() {
    var xMar = $('.fixed-container').outerHeight(); 
    $('.scrolling-container').css({"margin-top":xMar+"px"});
}
$(document).ready(function(){
    extraMargin();
});
$(window).resize(function(){
    extraMargin();
});

This will run extraMargin() function when the page loads and when the page is resized.

Here's a fiddle

Upvotes: 1

Richa
Richa

Reputation: 4270

Actually repeat the complete code on resize window function too:

$( window ).resize(function() {
   var fixedHeight = $(".fixed-container").outerHeight(true);
  $(".scrolling-container").css({"float":"left", "margin-top":fixedHeight + px"});
});

Upvotes: 0

Amaranadh Meda
Amaranadh Meda

Reputation: 724

I hope the following steps work if i understand your problem in right way .

$(document).ready( function(){
    var fixedHeight = $(".fixed-container").outerHeight(true);
     fixedHeight = (fixedHeight/screen.height)*100
    $(".scrolling-container").css("margin-top", fixedHeight + "%");
});

Upvotes: 0

Related Questions