Reputation: 2695
I have div
with margin:auto;
and I need get only margin-left
size value using javascript :)
//css
.test{
margin: auto;
width: 100px;
height: 100px;
outline: 1px solid red;
}
// html
<div class="test">Test</div>
Upvotes: 9
Views: 20785
Reputation: 505
You can use window.getComputedStyle() method if you don't need IE8 support.
var test = document.querySelector('.test');
var left_margin = window.getComputedStyle(test).getPropertyValue("margin-left"); // returns margin e.g. '655px'
left_margin = left_margin.match(/\d+/); //returns bare number e.g. '655'
Upvotes: 8
Reputation: 1743
Use this:
1) With jQuery
var left = $(".test").offset().left;
2) Or, second version is that:
Replace your div to <div class="test" id="test"></div>
, and use this js.
var left = document.getElementById("test").offsetLeft;
Upvotes: 10
Reputation: 2523
You don't need jQuery for that, plain JavaScript is enough:
var left, element = document.querySelector('.test');
if(element) {
left = element.getBoundingClientRect().left;
}
Upvotes: 1