曲径通幽论坛
标题: 外边距(margin) [打印本页]
作者: beyes 时间: 2016-12-28 13:52
标题: 外边距(margin)
示例一:
在没有左外边距描述的时候:
[HTML] 纯文本查看 复制代码
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<p>这个段落没有指定外边距。</p>
<p class="leftmargin">这个段落带有指定的左外边距。</p>
</body>
</html>
效果:
[attach]4810[/attach]
增加外边距描述:
<style type="text/css">
p.leftmargin {margin-left: 2cm}
</style>
效果:
[attach]4811[/attach]
示例二:
在没有右外边距描述的时候:
[HTML] 纯文本查看 复制代码
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<div>
<p>这个段落没有指定外边距。</p>
<p class="rightmargin">这个内容较长的段落我们指定了右外边距请比较相应的距离</p>
</div>
</body>
</html>
效果:
[attach]4812[/attach]
指定右外边距的时候:
[HTML] 纯文本查看 复制代码
<html>
<head>
<style type="text/css">
div {
width:8cm;
}
p.rightmargin {margin-right: 5cm}
</style>
</head>
<body>
<div>
<p>这个段落没有指定外边距。</p>
<p class="rightmargin">这个内容较长的段落我们指定了右外边距请比较相应的距离</p>
</div>
</body>
</html>
效果:
[attach]4813[/attach]
如上图所示,div 的宽度定义为 8cm ,但 p 通过类 rightmargin 声明保留外边距 5cm ,于是当这个段落的文字超过 3cm 时,在文字顶到 3cm 时,会自动换行。
示例三:
指定上外边距代码:
[HTML] 纯文本查看 复制代码
<html>
<head>
<style type="text/css">
p.topmargin {margin-top: 5cm}
</style>
</head>
<body>
<p>这个段落没有指定外边距。</p>
<p class="topmargin">这个段落带有指定的上外边距。</p>
</body>
</html>
效果:
[attach]4814[/attach]
示例三和示例二有所不同,示例二是段落与父元素div之间的空白是其外边距;示例三中第二个段距离第一个段是 5cm,这两个段并非父子关系,而是各自独立的。因此外边距的定义是 “围绕在元素边框的空白区域是外边距。”,设置外边距会在元素外创建额外的 “空白” 。
示例四
指定下外边距代码:
[HTML] 纯文本查看 复制代码
<html>
<head>
<style type="text/css">
p.bottommargin {margin-bottom: 2cm}
</style>
</head>
<body>
<p>这个段落没有指定外边距。</p>
<p class="bottommargin">这个段落带有指定的下外边距。</p>
<p>这个段落没有指定外边距。</p>
</body>
</html>
效果:
[attach]4815[/attach]
外边距的 margin 属性接受任何长度单位,百分数或负值都可以。margin 的默认值是 0,但如果你没给出一个 margin 值,就不会出现外边距。但实际上,浏览器通常已经为许多元素提供了预定的样式,外边距也不例外。因此,即使你不指定外边距,浏览器也会给出一个默认的,这也就是你会看到不同的段落之间会有 “空行” 。当然,如果你明确指定了外边距,那么就会覆盖浏览器默认的值。
如同上面所示,可以通过 margin-top, margin-right, margin-bottom, margin-left 分别指定出上、右、下、左 4 个方向的外边距。
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) |
Powered by Discuz! X3.2 |