Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  77] [ 2]  / answers: 1 / hits: 62506  / 12 Years ago, sat, november 17, 2012, 12:00:00

How do you get an element's inner height, without padding and borders?



No jQuery, just pure JS, and a cross-browser solution (IE7 included)



enter


More From » dom

 Answers
36

clientHeight - give the height including padding but without the
borders.



getComputedStyle - a way to tap into the CSS rules of an element and retrieve a property's value (padding)



Using parseInt is a way to strip away units and leave only the numeric value (which is in pixels)

parseFloat can also be used for more precise sub-pixel measurements




Note that all values will automatically be converted by the DOM API to pixels




function getInnerHeight( elm ){
var computed = getComputedStyle(elm),
padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom);

return elm.clientHeight - padding
}


DEMO:





// main method
function getInnerHeight( elm ){
var computed = getComputedStyle(elm),
padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom);

return elm.clientHeight - padding
}

// demo utility function
function printInnerHeight( selector ){
console.clear()
console.log(
getInnerHeight( document.querySelector(selector) )
)
}

body{ display: flex; padding:0; margin: 0; }
div{ flex: 1; }

.demo1{
padding-top: 2vh;
padding-bottom: 1vh;
margin: 30px;
border: 10px solid salmon;
box-sizing: border-box;
outline: 1px solid red;
}

.demo2{
padding-top: 2vh;
padding-bottom: 4vh;
margin: 30px;
border: 10px solid salmon;
border-bottom-width: 0;
height: 150px;
outline: 1px solid red;
}


p::before{
content: '';
display: block;
height: 100%;
min-height: 50px;
background: lightgreen;
}

<div>
<h2>inner height should be ~50px</h2>
<button onclick=printInnerHeight('.demo1')>Get Inner Height</button>
<p class='demo1'></p>
</div>
<div>
<h2>inner height should be ~150px</h2>
<button onclick=printInnerHeight('.demo2')>Get Inner Height</button>
<p class='demo2'></p>
</div>




[#81935] Friday, November 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;