Categories
JavaScript Answers jQuery

How to Set Margin CSS Properties with JavaScript?

Spread the love

Sometimes, we want to set margin CSS properties with JavaScript.

In this article, we’ll look at how to set margin CSS properties with JavaScript.

Set Margin CSS Properties with JavaScript

To set margin CSS properties with JavaScript, we can call the css method to change the margin CSS properties.

For instance, if we have the following HTML:

<div>
  hello
</div>

Then we write:

$('div').css('margin-left', '100px');

to select the div with $('div').

Then we call the css method on the returned div jQuery object with the property key and value we want to set respectively.

Therefore, we set margin-left to 100px.

The unit must be included.

Now we should see a 100px left margin added to the div.

Conclusion

To set margin CSS properties with JavaScript, we can call the css method to change the margin CSS properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *