- Understanding clientHeight, offsetHeight & scrollHeight Properties in CSS
- offsetHeight
- scrollHeight
- Example (clientHeight)
- Output
- Example (offsetHeight)
- Output
- Example (scrollHeight)
- Output
- How to Get the Height of an Element Using CSS Only
- How can I get the height of an element using css only
- The CSS Route
- The jQuery Route
- How can I get the height of an element using css only
- The CSS Route
- The jQuery Route
- How to use CSS calc() with an element’s height
- Set div height to height of browser using CSS ONLY
- How can an html element fill out 100% of the remaining screen height, using css only?
- CSS get height of screen resolution
- Make a div fill the height of the remaining screen space
- 2015 update: the flexbox approach
- Working example
- dynamic div height with static footer (css only)
- get the height of the previous element
- JavaScript: 4 способа получить width и height элемента
- CSS Box Model
- box-sizing
- Как получить ширину и высоту элемента в JS?
- offsetHeight и offsetWidth
- clientHeight и clientWidth
- Метод getBoundingClientRect()
Understanding clientHeight, offsetHeight & scrollHeight Properties in CSS
clientHeight gives the measure of the height of an element including the padding. Note that border, margin, and scrollbar height (if renedered) are not included in this.
offsetHeight
offsetHeight gives the measure of the height of an element including the vertical padding, top and bottom borders. Margin is not including here.
scrollHeight
scrollHeight gives the measure of the height of an element including the vertical padding and the content which is not visible on the screen because of its overflow property.
The following examples illustrate clientHeight, offsetHeight, and scrollHeight.
Example (clientHeight)
#parent < margin-top: 10px; height: 200px; width: 200px; overflow: auto; margin: 20px; >#demo
Output
This will produce the following result −
Example (offsetHeight)
#parent < height: 180px; width: 180px; overflow: auto; margin: 20px; >#demo
Output
This will produce the following result −
Example (scrollHeight)
#parent < margin-top: 10px; height: 200px; width: 200px; overflow: auto; margin: 20px; >#demo
Output
This will produce the following result −
How to Get the Height of an Element Using CSS Only
How can I get the height of an element using css only
Unfortunately, it is not possible to «get» the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3’s transform:translateY(); rule.
The CSS Route
If we assume that your target div in this instance is 200px high — this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
>
In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it’s own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
The jQuery Route
If faking it isn’t going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($) < //wait for the document to load
$('.dynamic-height').each(function() < //loop through each element with the .dynamic-height class
$(this).css( 'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
>);
>);
>);
How can I get the height of an element using css only
Unfortunately, it is not possible to «get» the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3’s transform:translateY(); rule.
The CSS Route
If we assume that your target div in this instance is 200px high — this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
>
In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it’s own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
The jQuery Route
If faking it isn’t going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($) < //wait for the document to load
$('.dynamic-height').each(function() < //loop through each element with the .dynamic-height class
$(this).css( 'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
>);
>);
>);
How to use CSS calc() with an element’s height
I think you are trying to run script in a css syntax, which is NOT POSSIBLE.
calc() can do basic math operation with absolute values, it cannot find the height of an element and then perform math on it.
Set div height to height of browser using CSS ONLY
I’ve got this result: http://jsfiddle.net/ZC7BT/
How can an html element fill out 100% of the remaining screen height, using css only?
The trick to this is specifying 100% height on the html and body elements.
Some browsers look to the parent elements (html, body) to calculate the height.
html, body
height: 100%;
>
#Header
width: 960px;
height: 150px;
>
#Content
height: 100%;
width: 960px;
>
CSS get height of screen resolution
It is not possible to get the height of the screen from CSS. However, using since CSS3 you can use media queries to control the display of the template as per the resolution.
If you want to code on the basis of height using media queries, you can define style-sheet and call it like this.
Make a div fill the height of the remaining screen space
2015 update: the flexbox approach
There are two other answers briefly mentioning flexbox; however, that was more than two years ago, and they don’t provide any examples. The specification for flexbox has definitely settled now.
Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.
(taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes)
All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim.
To check current support you can also see here:
http://caniuse.com/#feat=flexbox
Working example
With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I’ve added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.
html,body < height: 100%; margin: 0;>
.box < display: flex; flex-flow: column; height: 100%;>
.box .row < border: 1px dotted grey;>
.box .row.header < flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */>
.box .row.content < flex: 1 1 auto;>
.box .row.footer
header
(sized to content)
content (fills remaining space)
footer (fixed height)
dynamic div height with static footer (css only)
.data-box-row-wrapper height: calc(100vh - (24px + 24px + 24px + 24px + 125px + 38px + 24px + 24px));
>
.data-box-row-wrapper height: calc(100vh - 283px);
>
283 is sum of your static sections height, including their padding and margin.
body < background-color: gray; height: 100%; overflow-y: hidden;>
.configuration-drawer-container < background-color: #fff; bottom: 0; color: #333; font-size: 15px; font-weight: 300; height: 100vh; padding: 24px 24px 0 24px; position: absolute; top: 0; z-index: 9998;>.data-box-row-wrapper < height: calc(100vh - (24px + 24px + 24px + 24px + 125px + 38px + 24px + 24px));>.configuration-drawer-container-open < height: 100vh; /*overflow-y: auto;*/ visibility: visible; width: 480px; right: 0;>
.configuration-drawer-body < min-height: 100%; position: relative;>
.configuration-drawer-content < position: relative; height: 100%; heigth: calc(100vh - 500px); overflow: auto; /* padding-bottom: 90px; */>
.title-row-wrapper < margin-bottom: 24px; position: relative; width: 100%;>
.title < color: #333; display: inline; font-size: 20px; font-weight: 500;>
.data-box-row-wrapper < overflow-y: auto; background-color: light-gray; border: 1px red solid;>
.configuration-drawer-data-box-row < align-items: center; border-bottom: 1px solid #eee; cursor: pointer; display: flex; height: 48px; text-align: left;>
.button-wrapper < padding: 24px 0;>
.cancel < color: #007ec2; margin-right: 16px; padding: 0 8px 0 8px; border: 1px solid black; display: inline-block; font-size: 14px; font-weight: 500; height: 36px; line-height: 36px; min-width: 64px; text-align: center; vertical-align: middle;>
.save
Dashboard Configuration Select the data tiles you want displayed on the PM Dashboard.
Note: Dashboard configurations are shared across all workspaces of the same type. Changes to the configuration will affect other workspaces.
Select up to five rows
Option 1 Option 2 Option 3 Option 4 Option 5 Option 6 Option 7 Option 8 Option 9 Option 10 Option 11 Option 12 Option 13 Option 14 Option 15 Option 16 Option 17 Option 18 Option 19 Option 20 Close Save
get the height of the previous element
You can easily achieve the effect you’re looking for using flexbox. The trick is to allow the blue container (the one with the flexible height) to grow in size whenever the need arises, using flex: 1 1 auto , which is simply a shorthand for:
flex-grow: 1;
flex-shrink: 1;
flex-basis: auto;
See proof-of-concept code snippet below:
body < padding: 0; margin: 0;>.wrapper < display: flex; flex-direction: column; flex-wrap: no-wrap; align-items: center; justify-content: center; height: 100vh;>.wrapper > div < width: 100%;>#c1 < background-color: #880015; color: #fff; height: 60px; margin-bottom: 10px;>#c2 < background-color: #ff7f27; >#c3
height: 60px height: auto (determined by content?) flexible height
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