Changing Padding Using Javascript

When you create a webpage, and it is loaded on the browser, everything looks good. However, when the user interacts with your webpage, the perfect look may change or become distorted.

There are two ways you can go about doing this.

So, you want to make changes to the amount of padding once a user adds something on a web page. Therefore, it is important to know how to make such changes using javascript.

1. Using CSS and Javascript

Identify the element that need a change in the amount of padding.

<div id="changing-div">
  This is the a div element that we shall change its padding size

Create a CSS class with the new padding that you want to be applied.

.change-padding {

We are now going to add the new padding. We just add the class to our element that need changing through Javascript.

document.getElementById("changing-div").className = "change-padding";

2: Using Javascript only

We can make padding changes to a html element directly through javascript.

Javascript already has methods that can be used to make such changes. So let do this.

To make change all the paddings use .style.padding:

document.getElementById("changing-div").style.padding="30px 50px 30px 50px";

To change the top padding only use .style.paddingTop:


To change the right padding only use .style.paddingRight:


To change the bottom padding only use .style.paddingBottom:


To change the left padding only use .style.paddingLeft:

  1. Revert the padding to previous state

You may want to revert to the previous padding size if the user undos the previous action. To do this you will have to undo the changes you made.

For method 1, you just need to remove the class you added from the HTML element.


For method 2, you will need to  set the padding to the previous size.

To revert all padding to its previous state use .style.padding:

document.getElementById("changing-div").style.padding="20px 30px 20px 30px";


To  revert the top padding only to its previous state use .style.paddingTop:


To revert the right padding only to its previous state use .style.paddingRight:


To revert the bottom padding to its previous state only use .style.paddingBottom:


To change the left padding only use .style.paddingLeft:


I prefer method 1 since:

However, which ever method you choose, both methods will work.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.