5

Here is a simple triangle(non-isosceles):

enter image description here

#triangle-up {
  width: 0;
  height: 0;
  border-left: 30px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}
<div id="triangle-up"></div>

How can I calculate its height in javascript?

Ver Nick
  • 253
  • 8
  • 19
  • Does it have to be a formula to calculate? Isn't the height just equal to the border bottom value – Andy Feb 02 '19 at 14:09
  • you may think the duplicate is wrong, but the duplicate will explain you how the triangle is built thus you will know each dimension and you will be able to identify the height (like this one : https://stackoverflow.com/a/15546077/8620333) – Temani Afif Feb 02 '19 at 15:19
  • @TemaniAfif If you really think so, I won't argue with you, because you are an experienced user on this site and you know better. – Ver Nick Feb 03 '19 at 10:50
  • I don't know better and if you don't agree, you can still say *why* and argue. I can probably try to give more argument to convince you – Temani Afif Feb 03 '19 at 10:55

3 Answers3

5

Simply use DOM offsetHeight to get the real height (including paddings and borders, but excluding outlines) of an object:

var height=document.getElementById("triangle-up").offsetHeight;
console.log(height)
#triangle-up {
  width: 0;
  height: 0px;
  border-left: 30px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}
<div id="triangle-up"></div>
FZs
  • 16,581
  • 13
  • 41
  • 50
3

The height is the 100px red border.

The full width is 80px: The left side from the top tip to the left tip horizontally is 30px. The right side from the top tip to the right tip horizontally is 50px.

How to get this in Javascript:

const triangle = document.querySelector('#triangle-up');
const trianlgeStyles = window.getComputedStyle(triangle);
const triangleHeight = triangleStyles['border-bottom-width'];
Matty J
  • 988
  • 9
  • 13
2

The height of the triangle will be bottom-border - top-border. In the snippet as you can see when the top border is shown it is directly above the bottom border and from the bottom the bottom-border extends 100px till the top, hence giving it the height of 100px.

#triangle-up {
  width: 0;
  height: 0px;
  border-left: 30px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
  border-top: 1px solid black;
}
<div id="triangle-up"></div>
ellipsis
  • 12,049
  • 2
  • 17
  • 33