How to get an element's padding value using JavaScript?
To capture an element's padding in JavaScript, we use window.getComputedStyle
. This method is workable across all modern browsers starting from IE9. Here's a quick look:
In this snippet, compStyle
retains the computed styles, covering the padding values for each facet of the element.
Breaking down the getComputedStyle method
Computed styles are the end-result styles taken after assessing inline styles, stylesheet rules, and browser default styles. The getComputedStyle
method fetches a live CSSStyleDeclaration
object, encapsulating the element's styles. This means any padding set using em, rem, or percentage values is translated into pixel equivalent by getComputedStyle
.
Translating the returned value
Now beieving in the power of numbers over strings, we convert the returned padding value from a string to integer/float using parseInt
or parseFloat
:
The elephant in the browser (IE8 and older)
Heads-up, getComputedStyle
might give the cold shoulder to IE8 and earlier versions. So if you're working on projects supporting these browsers, consider crafting some fallback code or embracing a library that plugs these disparities.
Inline styles, the heroes within
If padding gets set inline, getting it through the element's style attribute is more straight-cut:
Nevertheless, this method shows its colors only for styles applied directly via the element's style
attribute, not for those flowing through external or internal CSS.
Advanced ways to get your hands on padding
We know getComputedStyle
is robust, but it's not the best at breaking down individual padding values if we query element.style.padding
. So here's how you can get individual padding values:
Collect them all
To dissect individual padding values to molecular level:
Responsive padding: Dealing with chameleons
Ever vigilant, padding might go chameleon on you depending on different screen sizes, especially if it's set with relative units or CSS media queries. Always exercise caution to derive the padding value in a responsive environment.
Cashing in on computed styles (Caching, not Typo)
For scripts feasting on getComputedStyle
a bit too much, it's healthy to cache the result for a performance boost:
Special notes
Shorthand properties? Overjoyed!
getComputedStyle
beams even when dealing with shorthand properties, giving back individual side values.
Visual vs. layout padding
Remember, padding can be your ally or your enemy. Depending on the situation, it could either be cosmetic, giving a visual breather, or functional, affecting the flow of the document.
Apt accessibility
Changing padding without forethought could disrupt the usability and accessibility of your web page. Look out for your end-users relying on keyboard navigation or screen readers.
Live demo
JSFiddle is to the rescue with this live example:
Witness how padding values change with a whimsical click.
Was this article helpful?