Set the left margin of a <div> element:
document.getElementById("myDiv").style.marginLeft = "50px";
Try it Yourself »
The marginLeft property sets or returns the left margin of an element.
Both the margin property and the padding property insert space around an element. However, the difference is that margin inserts the space around the border, while padding inserts the space within the border of an element.
Property | |||||
---|---|---|---|---|---|
marginLeft | Yes | Yes | Yes | Yes | Yes |
Return the marginLeft property:
object.style.marginLeft
Set the marginLeft property:
object.style.marginLeft
= "%|
length|auto|inherit"
Value | Description |
---|---|
% | Defines the left margin in % of the width of the parent element |
length | Defines the left margin in length units |
auto | The browser sets the left margin |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Default Value: | 0 |
---|---|
Return Value: | A String, representing the left margin of an element |
CSS Version | CSS1 |
Change the left margin of a <div> element back to "normal":
document.getElementById("myDiv").style.marginLeft = "0px";
Try it Yourself »
Return the left margin of a <div> element:
alert(document.getElementById("myDiv").style.marginLeft);
Try it Yourself »
Difference between marginLeft and paddingLeft:
function changeMargin() {
document.getElementById("myDiv").style.marginLeft = "100px";
}
function changePadding() {
document.getElementById("myDiv2").style.paddingLeft = "100px";
}
Try it Yourself »
CSS tutorial: CSS Margin
CSS reference: margin-left property
HTML DOM reference: margin property
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!