Gavin Sellers
Gavin Sellers

Reputation: 664

How can you get the height of an element with height:auto?

I'm trying to set the height of one element to the height of another by using javscript, and I've tried using the jquery height() method but it doesn't work because one of the element's has height set to auto:

#content
{
    background-color:#F2F2F2;
    width:1000px;
    margin:0px auto;
    text-align:left;
    min-height:900px;
    height:auto;
    border-top:5px solid #032F76;
    border-bottom:5px solid #032F76;
    overflow:auto;
}

So is there any easy way to get the height of an element who's height is set to auto?

Upvotes: 1

Views: 4968

Answers (4)

Kirill Fuchs
Kirill Fuchs

Reputation: 13696

heres a sample of my code:

$(document).ready(function() {
  CenterFrameSizer();
});

function CenterFrameSizer(){
  // Sets the left box and the center box the same height.
  if ( $("#leftbox").height() > $("#contentbox").height() ) {
    $("#contentbox").height($("#leftbox").height());
  } else {
    $("#leftbox").height($("#contentbox").height());
  }
}

function GalleryResize(){
  if ( $("#leftbox").height() > $("#gallery").height() ) {
    $("#gallery").height($("#leftbox").height());
  } else {
    $("#leftbox").height($("#gallery").height());
  }
}

Upvotes: 0

Ajay
Ajay

Reputation: 100

Just use this code

$('#content').height();

Upvotes: 0

Timeout
Timeout

Reputation: 7909

jQuery's .height() method still returns the numerical height value even if it's set to auto. BUT make sure you take margin, padding and borders into consideration.

I ran a test with your CSS just to make sure and .height() works fine.
http://jsfiddle.net/ysMge/8/

jQuery has 3 height calculating functions that take the margin, padding and border values into account differently.

Please review:

$("#content").height()
$("#content").outerHeight()
$("#content").innerHeight()

http://api.jquery.com/height/
http://api.jquery.com/outerHeight/
http://api.jquery.com/innerHeight/

Upvotes: 3

David Thomas
David Thomas

Reputation: 253318

You can use getComputedStyle:

var elem = document.getElementById('content');
var height = window.getComputedStyle(elem,null).getPropertyValue('height');

Which should return the computed height, in pixels, of the element.

A somewhat contrived JS Fiddle example.

Upvotes: 3

Related Questions