Javascript Reference - HTML DOM Style left Property








The left property sets or gets the left position of a positioned element.

Browser Support

left Yes Yes Yes Yes Yes

Syntax

Return the left property:

var v = object.style.left 

Set the left property:

object.style.left='auto|length|%|initial|inherit'

Property Values

ValueDescription
auto Default value. The browser does the calculation.
length Set left in px, cm, etc. Negative values allowed
% Sets the left edge position in % of containing element. Negative values allowed
inherit Inherit the left property from the parent element




Technical Details

Default Value: auto
Return Value: A string representing the left position
CSS Version CSS2

Example

The following code shows how to set the left position of a <button> element.


<!DOCTYPE html>
<html>
<head>
<style>
#myBtn {<!-- ww  w  .  java  2s  .  co  m-->
    position: absolute;
}
</style>
</head>
<body>

<button type="button" id="myBtn" onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementById("myBtn").style.left = "100px";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to set the left position of a <div> element.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--from   www . j a  v a 2  s  .co  m-->
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: coral;
    color: white;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">myDIV</div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.left = "100px";
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to use negative values in left position of a <div> element.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--from   w w w . ja  va2s .  c o  m-->
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: coral;
    color: white;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">myDIV</div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.left = "-30px";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to get the left position of a <div> element.


<!DOCTYPE html>
<html>
<body>
<!--  www . ja  v a  2 s.c o  m-->
<div id="myDiv" style="position:absolute;left:255px;">This is a div element.</div>

<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    console.log(document.getElementById("myDiv").style.left);
}
</script>

</body>
</html>

The code above is rendered as follows: