Get width in pixels from element with style set with %?
To transform an element's width from percentages to pixels, tap into JavaScript's getComputedStyle
for precision, including the padding and borders in the measurement:
getComputedStyle
provides the rendered style of the element. The width
property’s value is the exact pixel width, regardless of whether the original CSS value was a percentage.
JavaScript properties for pixel calculation
Using clientWidth
clientWidth
yields the width that includes padding but excludes borders and scrollbars. It's a direct and reliable measurement for inner width.
Resorting to offsetWidth
offsetWidth
calculates the width, factoring in the padding, borders, and scrollbar. An all-inclusive measurement.
Watch out! If width is set in percentages, elem.style.width
will return the same percentage and not an equivalent pixel value.
When jQuery comes to rescue
jQuery's .width()
furnishes the computed width in pixels. Forget all the pitfalls of raw JavaScript.
Manual calculations in complex scenarios
For certain situations, manual computations are necessary. Margins are not part of offsetWidth
. If you require the full width, it involves separately fetching margins from getComputedStyle
and adding them to offsetWidth
.
Remember, clientWidth
and offsetWidth
values could differ due to scrollbar width, so pick the one that suits your case (with or without the scrollbar look).
To set width using pixels explicitly, you can directly assign it like so:
Navigating the complexity: Scrollbars and borders
Scrollbar Calculations
Some loves are complex; so is the love for scrollbars in width calculations:
clientWidth
ignores the scrollbar width (keeping the relationship exclusively with inner width).offsetWidth
includes it, occasionally adding more drama to your layout calculations.
If scrollbar size is significant for your calculations, you might need to account for its width separately:
Evaluating borders
Borders can make width calculations more challenging. Remember, clientWidth
excludes them, while offsetWidth
includes them in its considerations.
When you want to accommodate border size absolutely, derive it using getComputedStyle
:
Was this article helpful?