Val Do
Val Do

Reputation: 2695

How to get margin left size using javascript when I use margin auto property in css

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>

Live example

Upvotes: 9

Views: 20785

Answers (3)

Tom
Tom

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

Sherali Turdiyev
Sherali Turdiyev

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

gaelgillard
gaelgillard

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

Related Questions