语法
margin: length | auto | initial | inherit;
边距属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> p { background-color: #1c87c9; color: #fff; margin: 25px 10px 15px 20px; } </style> </head> <body> <h2>Margin 属性示例</h2> <p>具有背景颜色、颜色和边距属性的段落。</p> </body> </html>
margin 属性的示例,其中元素的所有边的边距都设置为 10%:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> p.example { margin: 10%; } </style> </head> <body> <h2>Margin 属性示例</h2> <p>我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> <p class="example">我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> <p>我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> </body> </html>
定义为“em”的边距属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> p.example { margin: 4em; } </style> </head> <body> <h2>Margin 属性示例</h2> <p>我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> <p class="example">我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> <p>我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</p> </body> </html>
让我们看一下以下示例,该示例显示了边距、填充和边框属性之间的区别:
带有填充和边框属性的边距属性示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> div { background-color: #eee; width: 200px; border: 20px solid #8ebf42; padding: 30px; margin: 55px; } </style> </head> <body> <h2>Margin 属性示例</h2> <div>我爱你时你正一贫如洗寒窗苦读,离开你时你正金榜题名洞房花烛。</div> </body> </html>
CSS margin 属性用于在元素周围创建空间。
margin 属性是以下属性的简写:
- margin-top
- margin-bottom
- margin-left
- margin-right
我们可以同时对所有边(顶部、底部、左侧、右侧)使用 margin 属性。
对于顶部,我们使用 margin-top,对于底部 margin-bottom,对于左侧 margin-left 和对于右侧 margin-right。
边距属性可以定义为一、二、三或者四个值:
- 边距:25px 10px 15px 20px。这段代码意味着顶部边距必须为 25px,右侧边距为 10px,底部边距为 15px,左侧边距为 20px。
- 边距:15px 10px 20px。这意味着顶部的边距必须为 15px,左右两侧的边距为 10px,底部的边距为 20px。
- 边距:15px 10px。此代码表示上下边距为 15px,左右边距为 10px。
- 如果边距只有一个值,它将应用于所有四个值。
负值有效。
顶部和底部边距对内联元素没有影响,例如 <span> 或者 <code>。
初始值 | 0. |
---|---|
应用于 | 所有元素。 |
继承 | 无效 |
可动画的 | 是的。外轮廓是有动画的。 |
版本 | CSS1 |
DOM 语法 | object.style.margin =“20px 10px”; |
CSS margin 属性值说明
值 | 描述 |
---|---|
auto | 设定边距。这是此属性的默认值。 |
length | 定义PX,PT,CM等中的余量。默认值为0。 |
% | 将余量设置为包含元素的%。 |
initial | 使属性使用其默认值。 |
inherit | 从父母元素继承属性。 |
日期:2020-06-02 22:14:38 来源:oir作者:oir