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会出现坍塌,而这里是父子两个元素。
margin collapse_第1张图片
 期望结果:


margin collapse_第2张图片

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.

你可能感兴趣的:(margin)