jQuery width and height methods
The width
and height
methods get, respectively, the width and height of the element's content without taking into account padding
, border
and margin
.
Let's get the width and height values of the paragraph #test
and output them to another paragraph. Let's take the following HTML code as an example:
<p id="test">text</p>
<p id="out"></p>
CSS The paragraph style looks like this:
p {
margin: 10px;
padding: 5px;
}
Now we write the Javascript code:
let w = $('#test').width();
let h = $('#test').height();
$('#out').text('Width: ' + w + ' Height: ' + h);
We can also easily change the width and height values of elements using these methods. For example, let's set the width of the div #test1
to 250px
, and the height of #test2
to 200px
:
$('#test1').width(250);
$('#test2').height(200);
We have this layout:
<div id="wrapper">
<div id="test">text</div>
</div>
<p id="one"></p>
<p id="two"></p>
<p id="three"></p>
<p id="four"></p>
The following CSS styles:
div {
margin: 10px;
padding: 5px;
border: 2px solid green;
}
#wrapper {
border-color: blueviolet;
}
Get and output the width and height values of the div #wrapper
excluding padding and borders. Output the values in the first paragraph under this div.