Html div height javascript

How to get the rendered height of an element ?

To get the height of an element, there are five common methods in JavaScript. Lets see the differences between each and when they should be used. Only the last method gives the correct rendered height instead of the layout height.

  • style.height
  • jQuery( height, innerHeight, outerHeight )
  • clientHeight, offsetHeight, scrollHeight
  • getComputedStyle
  • getBoundingClientRect().height

Rendered height is the height that the element gets finally after all the styles and transformations are applied on that element. For example, An element has height of 100px and then gets a transform:scale(0.5). Its rendered height is 50px (after the transformation) and layout height is 100px.

style.height We can use style.height on any selected element and it will return its height. Does not include the padding, border or margin. Italways return the height along with the specific unit.

Note: Only works if we explicitly set the height as inline using the style attribute in HTML.

let height = document.getElementById("someId").style.height;

HTML

Output:
It returns empty string for “div1” and it returns “100px” for “div2”

  • For “div1”:
  • For “div2”:

Conclusion: It returns whatever height is specified in inline style attribute only. It does not factor in any transformations, like scale. It is not reliable and should not be used as inline styles are not ideal.

jQuery(height, innerHeight, outerHeight)
height() It returns the current height of the element. It does not include the padding, border or margin. It always returns a unit-less pixel value.

Читайте также:  Python static class members

Note: The height() will always return the content height, regardless of the value of CSS box-sizing property.

HTML

Output:
It returns unit-less pixel value as 100.

Output:

innerHeight() It returns the current height of the element including the top and bottom padding but not border. It always returns a unit-less pixel value.

let height = $("#div1").innerHeight();

HTML

Output:
It returns 120 which is (10(top padding) + 100(content height) + 10(bottom-padding))

outerHeight() It returns the current height of the element including the padding, border and margin optionally. It always returns a unit-less pixel value.

let height = $("#div1").outerHeight(); let height = $("#div1").outerHeight();

HTML

(1(top border)+ 10(top padding)+ 100(content height)+1 0(bottom-padding)+ 1(bottom border)

Note: The value reported by height(), innerHeight() and outerHeight() is not guaranteed to be accurate when the element or its parent is hidden. To get accurate results, ensure the element is visible before using these methods. jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery.

// If you need height of div excluding margin/padding/border $('#div1').height(); // If you need height of div with padding but without border + margin $('#div1').innerHeight(); // If you need height of div including padding and border $('#div1').outerHeight(); // For including border + margin + padding, can use $('#div1').outerHeight(true);

All these return only the layout height, not the rendered height.

clientHeight, offsetHeight, scrollHeight
clientHeight() It returns the height of the displayed content from the element (including vertical padding but not border or margin or scrollbar). It always returns an integer value in pixels. If element is hidden, then 0 is returned. If its a scrollable element, then it will only give the height of the visible part.

let height = document.getElementById("div1").clientHeight;

Источник

Читайте также:  Что такое атрибут объекта python

JavaScript: 4 способа получить width и height элемента

Как получить ширину и высоту HTML элемента с помощью обычного (чистого) JavaScript. Vanilla JavaScript (нативный JavaScript) уже давно позволяет кроссбраузерно получить размеры HTML элемента, без использования сторонних библиотек вроде jQuery. Не все пользуются этой возможностью, возможно потому что у блока есть несколько размеров (с отступами и без них) и не всегда понятно как и какой получить и где и какой использовать. Давайте разберемся, как получить ширину и высоту элемента используя встроенные в браузер JS методы и чем они друг от друга отличаются.

CSS Box Model

Что такое Box Model и как она влияет на размеры элемента (ширину и высоту).

Элемент HTML можно представить как коробку (box), которая состоит из четырех областей (частей):

  • margin — внешний отступ — пустое пространство вокруг элемента.
  • border — рамка — вокруг контента.
  • padding — внутренний отступ — пустая пространство, вокруг контента.
  • content — текст и другие элементы.

box-sizing

Какая именно будет высота и ширина зависит от CSS свойства box-sizing :

  • box-sizing: content-box — размер коробки измеряется относительно контента.
    Т.е. говорит браузеру, что размеры указанные в width и height относятся только к контенту. А padding и border не входят в указанные width и height и добавляются дополнительно, делая размер всего элемента больше, чем указано в width и height.
  • box-sizing: border-box — размер коробки измеряется относительно border (рамки).
    Т.е. говорит браузеру, что в указанные размеры для width и height входит все: content, padding и border.

По умолчанию в браузерах используется box-sizing: content-box .

Как получить ширину и высоту элемента в JS?

Здесь есть как минимум четыре варианта. Каждый из них имеет свои особенности и подойдет в зависимости от того, какой именно размер вам нужен. Рассмотрим каждый.

Читайте также:  Функция фильтр в питоне

offsetHeight и offsetWidth

Содержат высоту и ширину элемента, включая padding и border (отступы и границы). Возвращаемое значение является целым числом и доступно только для чтения.

const element = document.querySelector( '.element' ); // int значение ширины: content + padding + border. element.offsetWidth; // 110 // int значение высоты: content + padding + border. element.offsetHeight; // 60

Значения округляются до целого числа (не float).

clientHeight и clientWidth

Содержат высоту и ширину элемента, включая padding (отступы), но исключая border (границы). Возвращаемое значение является целым числом и доступно только для чтения.

const element = document.querySelector( '.element' ); // int значение ширины: content + padding (без border). element.clientWidth; // 100 // int значение высоты: content + padding (без border). element.clientHeight; // 50

Значения округляются до целого числа (не float).

Метод getBoundingClientRect()

Метод getBoundingClientRect() возвращает объект, содержащий все размеры элемента и размеры его положения относительно области просмотра (viewport).

ВАЖНО: width и height метода getBoundingClientRect() вернут значение, основанное на свойстве CSS box-sizing элемента. Например, при box-sizing: border-box ширина и высота будут включать padding и border.

const element = document.querySelector( '.element' ); const rect = element.getBoundingClientRect() rect.width // 945.59 rect.height // 48.62 rect.right // 1162.79 rect.bottom // 132.44 rect.top // 83.82 rect.y // 83.82 rect.left // 217.19 rect.x // 217.19

Источник

Оцените статью