Get CSS position property of element with JavaScript

Issue

For example I have this <div> with the following CSS:

.some-div{
   position: relative;
   top: 50px;
}
<div class="some-div">
   <p>Some content</p>
</div>

How do I get the CSS property position of the element with JavaScript (which in this example should result in the string "relative")?

Solution

Window.getComputedStyle()

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain

const element = document.getElementById('your_element_id');
const computedStyles = getComputedStyle(element);
const position = computedStyles.position;

Answered By – shevchenko-vladislav

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.