How can I get the height of an element using css only

Viewed 173164

We have a lot of options to get the height of an element using jQuery and JavaScript.

But how can we get the height using CSS only?

Suppose, I have a div with dynamic content - so it does not have a fixed height:

.dynamic-height {
   color: #000;
   font-size: 12px;
   height: auto;
   text-align: left;
}
<div class='dynamic-height'>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
</div>

I want to set the margin-top of .dynamic-height to a value which is equal to (the height of the div - 10px) using CSS only.

If I get the height I can use CSS calc() function.

How do I do that?

5 Answers

Simplest & quickest solution is to try vanilla(plain) Javascript in your chrome developer console to calculate height or width of any element, just put any element's 'id' into this and get it calculated:

var clientHeight = document.getElementById('exampleElement').clientHeight;
alert(clientHeight);

var offsetHeight = document.getElementById('exampleElement').offsetHeight;
alert(offsetHeight)

There is no way using css. But,

We can achive it using a single line of JavaScript.

For finding height of div

document.getElementById("div-id").clientHeight

For finding width of div

document.getElementById("div-id").clientWidth

If you want move down the div it is very simple. Lets define a div with a .box class and define a height of 150px so if you run the snippet u will see the element.

Now lets convert the .box as a flexbox like this:

.box {
    display: flex;
    flex-flow: row;
    ...
}

Finally, lets move our div with .dynamic-height class to the bottom of its container with align-self: end like this:

.dynamic-height {
    align-self: end;
    ...
}

I also change the color of the .dynamic-height class to green so it help us to see the effect of the align-self: end.

.box {
  display: flex;
  flex-flow: row;
  height: 150px;
}

.dynamic-height {
  align-self: end;
  color: #000;
  font-size: 12px;
  background: green;
}
<div class='box'>
  <div class='dynamic-height'>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis.
    sem.
  </div>
</div>

Related