- How do I retrieve an HTML element’s actual width and height?
- 17 Answers 17
- HTMLElement: offsetHeight property
- Value
- Examples
- Specifications
- Notes
- Browser compatibility
- See also
- Found a content problem with this page?
- height
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Установка высоты с помощью пикселей и процентов
- HTML
- CSS
- Result
- Specifications
- height
- Интерактивный пример
- Синтаксис
- Значения
- Формальный синтаксис
- Пример
- HTML
- CSS
- Результат
- Проблемы доступности
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
How do I retrieve an HTML element’s actual width and height?
Suppose that I have a
Keep in mind that getting an element’s height through any method always has a performance impact as it makes the browser recalculate the position of all elements in the page (reflow). Therefore, avoid doing it too much. Checkout this list for what kind of things trigger a reflow.
17 Answers 17
You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style .
var width = document.getElementById('foo').offsetWidth;
The .getBoundingClientRect() function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms.
> console.log(document.getElementById('foo').getBoundingClientRect()) DOMRect
Beware! offsetHeight/offsetWidth can return 0 if you’ve done certain DOM modifications to the element recently. You may have to call this code in a setTimeout call after you’ve modified the element.
I can’t pinpoint the reason that offsetWidth is returning 0 in my case, because I didn’t originally write the code, but within the onload event I get always 0.
@JDandChips: offsetWidth will be 0 if the element is display:none , whereas the computed width might still have a positive value in this instance. visibility:hidden does not affect the offsetWidth .
@Supuhstar both have different meanings. offsetWidth returns the «whole» box including content, padding, and borders; while clientWidth returns the size of the content box alone (so it will have a smaller value whenever the element has any non-zero padding and/or border). (mod edited for clarity)
This method will return an object containing the width , height , and some other useful values:
var element = document.getElementById('foo'); var positionInfo = element.getBoundingClientRect(); var height = positionInfo.height; var width = positionInfo.width;
I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)
Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.
IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*
If you must support IE8, use .offsetWidth and .offsetHeight :
var height = element.offsetHeight; var width = element.offsetWidth;
Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn’t work out-of-the-box.)
- .offsetHeight : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
- .offsetWidth : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth
- .getBoundingClientRect() : https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
getboundingClientRect() will return the actual width and height of elements scaled via css whereas offsetHeight and offsetWidth will not.
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 and width (or outerHeight and outerWidth , as appropriate).
var height = $("#myDiv").height(); var width = $("#myDiv").width(); var docHeight = $(document).height(); var docWidth = $(document).width();
Just in case it is useful to anyone, I put a textbox, button and div all with the same css:
width:200px; height:20px; border:solid 1px #000; padding:2px;
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
Firefox Chrome IE-Edge with w/o with w/o with w/o box-sizing $("#t").width() 194 200 194 200 194 200 $("#b").width() 194 194 194 194 194 194 $("#d").width() 194 200 194 200 194 200 $("#t").outerWidth() 200 206 200 206 200 206 $("#b").outerWidth() 200 200 200 200 200 200 $("#d").outerWidth() 200 206 200 206 200 206 $("#t").innerWidth() 198 204 198 204 198 204 $("#b").innerWidth() 198 198 198 198 198 198 $("#d").innerWidth() 198 204 198 204 198 204 $("#t").css('width') 200px 200px 200px 200px 200px 200px $("#b").css('width') 200px 200px 200px 200px 200px 200px $("#d").css('width') 200px 200px 200px 200px 200px 200px $("#t").css('border-left-width') 1px 1px 1px 1px 1px 1px $("#b").css('border-left-width') 1px 1px 1px 1px 1px 1px $("#d").css('border-left-width') 1px 1px 1px 1px 1px 1px $("#t").css('padding-left') 2px 2px 2px 2px 2px 2px $("#b").css('padding-left') 2px 2px 2px 2px 2px 2px $("#d").css('padding-left') 2px 2px 2px 2px 2px 2px document.getElementById("t").getBoundingClientRect().width 200 206 200 206 200 206 document.getElementById("b").getBoundingClientRect().width 200 200 200 200 200 200 document.getElementById("d").getBoundingClientRect().width 200 206 200 206 200 206 document.getElementById("t").offsetWidth 200 206 200 206 200 206 document.getElementById("b").offsetWidth 200 200 200 200 200 200 document.getElementById("d").offsetWidth 200 206 200 206 200 206
HTMLElement: offsetHeight property
The HTMLElement.offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer.
Typically, offsetHeight is a measurement in pixels of the element’s CSS height, including any borders, padding, and horizontal scrollbars (if rendered). It does not include the height of pseudo-elements such as ::before or ::after . For the document body object, the measurement includes total linear content height instead of the element’s CSS height. Floated elements extending below other linear content are ignored.
If the element is hidden (for example, by setting style.display on the element or one of its ancestors to «none» ), then 0 is returned.
Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect() .
Value
Examples
The example image above shows a scrollbar and an offsetHeight which fits on the window. However, non-scrollable elements may have large offsetHeight values, much larger than the visible content. These elements are typically contained within scrollable elements; consequently, these non-scrollable elements may be completely or partly invisible, depending on the scrollTop setting of the scrollable container.
Specifications
Notes
offsetHeight is a property of the DHTML object model which was first introduced by MSIE. It is sometimes referred to as an element’s physical/graphical dimensions, or an element’s border-box height.
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
height
Свойство CSS height определяет высоту элемента. По умолчанию свойство определяет высоту области содержимого . Однако, если box-sizing установлен на border-box , он вместо этого определяет высоту области границы .
Try it
В min-height и max-height свойства переопределить height .
Syntax
/ * значения * / height: 120px; height: 10em; / * значение * / height: 75%; / * Значения ключевых слов * / height: max-content; height: min-content; height: fit-content(20em); height: auto; / * Глобальные значения * / height: inherit; height: initial; height: revert; height: revert-layer; height: unset;
Values
Определяет высоту как абсолютное значение.
Определяет высоту в процентах от высоты содержащего блока.
Браузер рассчитает и выберет высоту для указанного элемента.
Внутренняя предпочитаемая высота.
Внутренняя минимальная высота.
Box будет использовать доступное пространство, но не больше, чем max-content .
Использует формулу fit-content с заменой доступного пространства указанным аргументом, т.е. min(max-content, max(min-content, ))
Позволяет выбрать среднее значение в диапазоне значений между определенными минимумом и максимумом
Accessibility concerns
Убедитесь, что элементы, для которых задана height , не усечены и / или не закрывают другой контент при масштабировании страницы для увеличения размера текста.
Formal definition
Initial value | auto |
---|---|
Applies to | все элементы,кроме неперемещенных встроенных элементов,столбцов таблицы и групп столбцов. |
Inherited | no |
Percentages | Процент рассчитывается относительно высоты содержащего блока сгенерированного блока. Если высота содержащего блока не указана явно (то есть зависит от высоты содержимого), и этот элемент не является абсолютно позиционированным, значение вычисляется как auto . Процентная высота корневого элемента относительно исходного содержащего блока. |
Computed value | процент или auto или абсолютная длина |
Animation type | длина , процент или calc (); |
Formal syntax
height = auto | length-percentage [0,∞]> | min-content | max-content | fit-content( length-percentage [0,∞]> ) length-percentage> = length> | percentage>
Examples
Установка высоты с помощью пикселей и процентов
HTML
div id="taller">I'm 50 pixels tall. div> div id="shorter">I'm 25 pixels tall. div> div id="parent"> div id="child"> I'm half the height of my parent. div> div>
CSS
div < width: 250px; margin-bottom: 5px; border: 2px solid blue; > #taller < height: 50px; > #shorter < height: 25px; > #parent < height: 100px; > #child < height: 50%; width: 75%; >
Result
Specifications
height
CSS атрибут height позволят обозначать высоту элемента. По умолчанию, свойство определяет высоту внутренней области. Если box-sizing имеет значение border-box , то свойство будет определять высоту области рамки.
Интерактивный пример
Атрибуты min-height и max-height при добавлении меняют значение height .
Синтаксис
/* Значения-ключевые слова */ height: auto; /* значения */ height: 120px; height: 10em; /* значения */ height: 75%; /* Глобальные значения */ height: inherit; height: initial; height: unset;
Значения
Высота — фиксированная величина.
Высота в процентах — размер относительно высоты родительского блока.
border-box Экспериментальная возможность
content-box Экспериментальная возможность
Браузер рассчитает и выберет высоту для указанного элемента.
fill Экспериментальная возможность
Использует fill-available размер строки или fill-available размер блока, в зависимости от способа разметки.
max-content Экспериментальная возможность
Внутренняя максимальная предпочтительная высота.
min-content Экспериментальная возможность
Внутренняя минимальная предпочтительная высота.
available Экспериментальная возможность
Высота содержащего блока минус вертикальные margin , border и padding .
fit-content Экспериментальная возможность
- внутренняя минимальная высота
- меньшая из внутренней предпочтительной высоты и доступной высоты
Формальный синтаксис
height =
auto | (en-US)
(en-US) | (en-US)
min-content | (en-US)
max-content | (en-US)
fit-content( (en-US) )
=
| (en-US)
Пример
HTML
div id="taller">Я 50 пикселей в высоту.div> div id="shorter">Я 25 пикселей в высоту.div> div id="parent"> div id="child"> Моя высота - половина от высоты родителя. div> div>
CSS
div width: 250px; margin-bottom: 5px; border: 2px solid blue; > #taller height: 50px; > #shorter height: 25px; > #parent height: 100px; > #child height: 50%; width: 75%; >
Результат
Проблемы доступности
Убедитесь, что элементы с height не обрезаются и / или не затеняют другое содержимое, когда страница масштабируется для увеличения размера текста.
Спецификации
Начальное значение | auto |
---|---|
Применяется к | все элементы, кроме незаменяемых строчных элементов, табличных колонок и групп колонок |
Наследуется | нет |
Проценты | Процент для генерируемого блока рассчитывается по отношению к высоте содержащего блока. Если высота содержащего блока не задана явно (т.е. зависит от высоты содержимого), и этот этот элемент позиционирован не абсолютно, значение будет auto . Процентная высота на корневом элементе относительна первоначальному блоку. |
Обработка значения | процент, auto или абсолютная длина |
Animation type | длина, проценты или calc(); |
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 15 июл. 2023 г. by MDN contributors.
Your blueprint for a better internet.