Suppose that I have a <div>
that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div>
element.
What should I use? Please include information on browser compatibility.
Suppose that I have a <div>
that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div>
element.
What should I use? Please include information on browser compatibility.
also you can use this code:
Just in case it is useful to anyone, I put a textbox, button and div all with the same css:
I tried it in chrome, firefox and ie-edge, I tried with jquery and without, and I tried it with and without
box-sizing:border-box
. Always with<!DOCTYPE html>
The results:
NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.
As of jQuery 1.2.6 you can use one of the core CSS functions,
height
andwidth
(orouterHeight
andouterWidth
, as appropriate).... seems CSS help to put div on center ...
If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100
/\d*/.exec(MyElement.style.width)
It is easy to modify the elements styles but kinda tricky to read the value.
JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.
Element: The element to read the value for.
pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.
The result is an object with style properties, like elem.style, but now with respect to all css classes.
For instance, here style doesn’t see the margin:
So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute
Computed and resolved values
There are two concepts in CSS:
A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
So nowadays getComputedStyle actually returns the resolved value of the property.
Please Note:
getComputedStyle requires the full property name
There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:
for more information https://javascript.info/styles-and-classes