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?

4
  • Does it have to be a formula to calculate? Isn't the height just equal to the border bottom value Commented Feb 2, 2019 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 : stackoverflow.com/a/15546077/8620333) Commented Feb 2, 2019 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. Commented Feb 3, 2019 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 Commented Feb 3, 2019 at 10:55

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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'];

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.