jQuery

Changing The Element Size With jQuery

When you are changing the size of an element using jQuery there are two methods that you can use to change the size.

First you can use the .css() method passing in the first parameter as height or width and the second parameter being the value.

$('.element').css('height', new_height_value);

$('.element').css('width', new_width_value);

The other option is to use the .height() method and the .width() method.

$('.element').height(new_height_value);

$('.element').width(new_width_value);

In this article we are going to look at the difference between these two methods.

The difference in using height() method and .css('height', val) method is that the .height() method will calculate the element's padding, border and margin to set the height of the element. The css() method will simply change the height CSS property.

If you have an element with a padding, border and size.

<style>
.element
{
    border: 5px solid #a1a1a1;
    padding: 40px;

    height: 200px;
    width: 400px;
}
</style>

<div class="element"></div>

Using the .css() method it will simply add the height and width to the element.

<script>
$('#preview_css').css('height', 300);
$('#preview_css').css('width', 300);
</script>

<div class="element" style="height: 300px; width: 300px;"></div>

Using the .height() and .width() method it will calculate the padding, border and margin to the element and add these to the height to make sure that the height of the element is the defined value.

<script>
$('#preview_css').height(300);
$('#preview_css').width(300);
</script>

<div class="element" style="height: 390px; width: 390px;"></div>

View the demo to see the difference between the two functions.

Demo

Back to top

View Demo

Members Download