margin collapse

碰到margin无效问题,查的一些资料。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Margin</title>
<style type="text/css">
	.container{
		margin: 0 auto;
		width: 800px;
		padding: 0 10px 10px;
		outline: 1px solid red;
	}
	.item{
		height: 50px;
		margin-top: 10px;
		outline: 1px solid green;
	}
</style>
</head>
<body>
	<div class="container">
		<div class="item">默认margin</div>
		<div class="item"></div>
	</div>
</body>
</html>

 

实际结果:

第一个div的margin-top没生效,一般情况下是两个相邻的div的margin-bottom与margin-top会出现坍塌,而这里是父子两个元素。

 期望结果:


IE浏览器是由所谓的hasLayout引起:

1.该盒子加浮动;
2.用内边距来解决(给其父元素一个设置个内边距)
3.overflow:hidden;
4.给其父元素一个设置个border属性也可解决。
5.绝对定位

参考:

http://adamghost.com/2008/12/ie-haslayout-%E8%AF%A6%E8%A7%A3/

http://www.cnblogs.com/imhurley/archive/2011/11/23/2260764.html

 

 

对于非IE浏览器可查看下面的W3C规范: 

Here are the relevant points from the W3C spec:

8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse [...]

Two margins are adjoining if and only if:

  • both belong to in-flow block-level boxes that participate in the same block formatting context
  • no line boxes, no clearance, no padding and no border separate them
  • both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
    • top margin of a box and top margin of its first in-flow child

The reason why doing any of the following prevents the margin collapse:

Is because:

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).

The left and right margins behave as you expect because:

Horizontal margins never collapse.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值