Home  >  Article  >  Web Front-end  >  问题与对策:CSS的margin塌陷(collapse) - jerrylsxu

问题与对策:CSS的margin塌陷(collapse) - jerrylsxu

WBOY
WBOYOriginal
2016-05-20 13:49:181523browse

 

   2: 
   3: 
   4:     
   5:     
   6: 
   7: *{
   8:     margin:0px;
   9:     padding:0px;
  10: }
  11:  
  12: #no1{
  13:     background:#808000;
  14:     width:300px;
  15:     height:300px;
  16:     margin:100px 0 0 100px;
  17:     }
  18:  
  19: #no2{
  20:     background:#c0c0c0;
  21:     width:150px;
  22:     height:150px;
  23:     margin-left:20px;
  24:     margin-top:30px;
  25: }
  26: 
  27: 
  28:  
  29: 
  30:  
  31: 
  32:     
Span2
  33: 
  34:  
  35: 
  36:  
  37: 

如果您认为应该是这样的话:

1

    那就错了。结果是这样的:

2

     因为CSS中存在一个margin collapse,即边界塌陷或者说边界重叠。对于上下两个并列的div块而言,上面div的margin-bottom和下面div的margin- top会塌陷,也就是会取上下两者margin里最大值作为显示值,所以从这个意义上说:CSS及浏览器的设计者们希望我们在布局时,如果遇到上下两个并排内容块的安排,最好只设置其中每个块上或下margin的一处即可w3school也规定:当两个垂直外边距相遇时,它们将形成一个外边距。合并后的外边距的高度等于两个发生合并的外边距的高度中的较大者。

    但对于父块DIV内含子块DIV的情况,就会按另一条CSS惯例来解释了,那就是:对于有块级子元素的元素计算高度的方式,如果元素没有垂直边框和填充,那其高度就是其子元素顶部和底部边框边缘之间的距离。所以对于代码:

   1: 

father这个div的高度为0,因为里面没有能够撑开div的内容。如果变为:

   1: 
I am here.

则高度就是文字的高度,因为此时文字在撑着这个DIV。

    话说回来,一个DIV和它的子DIV特别重视垂直边框或填充,也就好像是,一口锅,里面放个盆,能不能扣住里面的盆,主要看锅盖了,垂直边框或填充就是这个“锅盖”。于是解决的方式至少有以下三种:

  1、需要给父div设置边框,当然可以设置边框为透明:

   1: border:1px solid transparent
   2: 或
   3: border-top:1px solid transparent

  2、为父DIV添加padding,或者至少添加padding-top;

   1: padding:1px
   2: 或
   3: padding-top:1px;   /*必须大于0*/

  3、为父DIV添加overflow:hidden 

   1: over-flow:hidden;

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn