CSS margin 属性是一个速记属性,它设置元素所有四个边的边距宽度。
可能的值
- length − 任何长度值。
- percentage − 边距的宽度是相对于元素的包含块的宽度计算的。
- auto − 设置要自动计算的所有四个边距的值。
适用于
所有 HTML 元素。
DOM 语法
object.style.margin = "5px"
CSS margin - 基本示例
以下示例演示了 CSS 属性 margin 的使用 -
<html>
<head>
<style>
p {
background-color: rgb(201, 238, 240);
border: 1px solid black;
width: fit-content;
}
.margin-one {
margin: 30px;
}
.margin-two {
margin: 20px 5%;
}
.margin-three {
margin: 10px 2% -5px;
}
.margin-four {
margin: 10px 2% -5px auto;
}
</style>
</head>
<body>
<p class="margin-one">
all four margins will be 30px.
</p>
<p class="margin-two">
top and bottom margin will be 20px, left and right margin will be 5%
of the total width of the document.
</p>
<p class="margin-three">
top margin will be 10px, left and right margin will be 2% of the
total width of the document, bottom margin will be -5px.
</p>
<p class="margin-four">
top margin will be 10px, right margin will be 2% of the total
width of the document, bottom margin will be -5px, left margin
will be set by the browser.
</p>
</body>
</html>