We can use jQuery to get the margin of an element simply by using the jQuery css() method to retrieve the margin property of the element.
$("#div1").css('margin');
Let’s see a simple example of this below.
Let’s say we have the following HTML:
If we want to get the margin of #div1, we will use the jQuery css() method and retrieve the margin in the following jQuery code.
var theMargin = $("#div1").css('margin');
console.log(theMargin);
#Output
40px
If you are using WordPress, don’t forget to change the $ to jQuery as below:
var theMargin = jQuery("#div1").css('margin');
Note that we can also get the padding of an element using the css() method.
Get Different Margin Values of an Element Using jQuery
Let’s say in our example above, that our div has different margin values for each side. Here is our HTML for that:
We can still use our same jQuery code to get the margin of the element with different values for each side.
var theMargin = $("#div1").css('margin');
console.log(theMargin);
#Output
40px 30px 20px 10px
We can also get the individual margin values for each side using jQuery. We just have to change the value in our css() method.
Here is how to get the margin for each side using jQuery:
var marginTop = $("#div1").css('margin-top');
var marginBottom = $("#div1").css('margin-bottom');
var marginLeft = $("#div1").css('margin-left');
var marginRight = $("#div1").css('margin-right');
console.log(marginTop);
console.log(marginBottom);
console.log(marginLeft);
console.log(marginRight);
#Output
40px
20px
10px
30px
Hopefully this article has helped you understand how to use jQuery to get the margin of an element.