如何使用 jQuery 从 DIV 中删除高度样式?

默认情况下,DIV 的高度由其内容决定。

但是,我覆盖了它,并使用 jQuery 显式地设置了高度:

$('div#someDiv').height(someNumberOfPixels);

我怎么才能扭转这种局面?我想删除高度样式,使它回到它的自动/自然高度?

109314 次浏览

maybe something like

$('div#someDiv').css("height", "auto");
$('div#someDiv').removeAttr("height");

To reset the height of the div, just try

$("#someDiv").height('auto');

to remove the height:

$('div#someDiv').css('height', '');
$('div#someDiv').css('height', null);

like John pointed out, set height to auto:

$('div#someDiv').css('height', 'auto');

(checked with jQuery 1.4)

$('div#someDiv').height('auto');

I like using this, because it's symmetric with how you explicitly used .height(val) to set it in the first place, and works across browsers.

you can try this:

$('div#someDiv').height('');

just to add to the answers here, I was using the height as a function with two options either specify the height if it is less than the window height, or set it back to auto

var windowHeight = $(window).height();
$('div#someDiv').height(function(){
if ($(this).height() < windowHeight)
return windowHeight;
return 'auto';
});

I needed to center the content vertically if it was smaller than the window height or else let it scroll naturally so this is what I came up with

Thank guys for showing all those examples. I was still having trouble with my contact page on small media screens like below 480px after trying your examples. Bootstrap kept inserting height: auto.

Element Inspector / Devtools will show the height in:

element.style {


}

In my case I was seeing: section#contact.contact-container | 303 x 743 in the browser window.

So the following full-length works to eliminate the issue:

$('section#contact.contact-container').height('');

$('div#someDiv').css('height', '');

I personally use unset

$('some-element').css('height', 'unset');

You may refer to this doc