Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 927
Val Do Avatar asked Sep 14 '15 12:09

Val Do


2 Answers

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'
like image 166
Lunokhod Avatar answered Oct 25 '22 05:10

Lunokhod


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;
like image 38
Sherali Turdiyev Avatar answered Oct 25 '22 06:10

Sherali Turdiyev