首页 > 开发 > CSS > 正文

CSS属性探秘系列(六):margin

2024-07-11 08:30:24
字体:
来源:转载
供稿:网友

一、属性介绍

margin 属性接受任何长度单位,可以是像素、英寸、毫米或 em。
可取值:
auto 浏览器计算外边距。
length 规定以具体单位计的外边距值,比如像素、厘米等。默认值是 0px。
% 规定基于父元素的宽度的百分比计算的外边距。
inherit 规定应该从父元素继承外边距。

二、常见问题

1.IE6下浮动元素双倍边距问题
解决方法:
IE6中设置block元素display:inline;
.l{margin-left:20px;float:left;display:inline;}
原因:首先,inline元素和inline-block元素是没有双倍边距的。对inline元素设置float后,会有个haslayout,使inline元素具有inline-block元素的特性,进而可以设置垂直margin、padding、width、height。

2.margin外边距合并问题
外边距的合并发生在以下三种情形:
情形一:空块元素
a)如果一个块级元素没有border、padding、inline content、height、min-height来分隔,设置margin-top和margin-bottom属性后会合并,

b)实例:


复制代码
代码如下:
<style type="text/css">
body{margin:0;}
.out{width:400px;border:1px solid #f00;margin:0 auto;background-color:#ccc;}
.inner{margin-top:40px;margin-bottom:40px;}
</style>
<div class="out">
<div class="inner"></div>
</div>

从上例可以看出,最后.out computed height为40px;
>=IE8、Firefox、Chrome测试效果相同。但是有个疑问,去掉out的边框后,其高度计算为0,不知道什么原因?

情形二:父元素与第一个或最后一个子元素
如果块元素的 margin-top 与它的第一个子元素之间没有border, padding, inline content, 或 clearance 分隔,或者块元素的 margin-bottom 与它的最后一个子元素之间没有padding, inline content, height, min-height, or max-height 分隔,那么外边距会合并。


复制代码
代码如下:
<style type="text/css">
body{margin:0;}
.parent{border:1px dotted #ccc;width:400px;}
.outer{height:50px;background-color:#f00;margin-top:40px;margin-bottom:40px;}
.inner01{margin-top:20px;background:#00f;}
.inner02{margin-bottom:60px;background:#f0f;}
</style>
<div class="parent">
<div class="outer">
<div class="inner01">inner01</div>
<div class="inner02">inner02</div>
</div>
</div>

>=IE6,FF,Chrome效果效果相同,此时inner01的margin-top:并没有起作用,这就是为什么很多人在网上问,我设置margin-top,margin-bottom不起作用的原因了!如下图:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表