CSS 基础 例子 盒子模型及外边距塌陷

   我们通常设置的宽度和高度,是指盒子模型中内容(content)的宽度和高度。元素的高度,还要加上上下padding和上下border,元素整个盒子的高度还要加上上下margin;宽度类似计算。

  注意:

  • 父子元素包含情况下的计算,父亲元素会把儿子元素的整个盒子(包括margin)的大小作为内容。
  • 外边距塌陷(margin collapse),块元素的 top 与 bottom 外边距有时会合并(塌陷)为单个外边距(合并后最大的外边距),这样的现象称之为 外边距塌陷。
  • 一般我们给元素设置背景色不会包括margin和border。

一、普通盒子

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title></title> 
<style>
.divcss
{ 
    width:300px; 
    border:5px solid #F00;
    margin:10px;
    padding:5px;
} 
</style>
</head>
<body>
<div class="divcss"> 
 我是盒子1
</div> 
<div class="divcss"> 
我是盒子2
</div>
</body>
</html>

  运行结果:

二、 父子盒子

  父子div盒子,外层div定义padding,内层div定义margin

  父亲元素会把儿子元素的整个盒子(包括margin)的大小作为内容

  html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title></title> 
<style>
*{
    margin:0;
    padding:0px;
    }
.divcss
{ 
    width:300px; 
    border:5px solid #eee;
    margin:10px;
    padding:5px;
} 
.divcss1
{ 
    margin:20px;
}
</style>
</head>
<body>
<div class="divcss"> 
 <div class="divcss1"> 
    我是盒子
</div>
</div> 

</body>
</html>

  运行结果:

  内层盒子:

  

  外层盒子:

  

三、外边距塌陷盒子

  块元素的 top 与 bottom 外边距有时会合并(塌陷)为单个外边距(合并后最大的外边距)

  两个上下相邻的DIV,margin都设置了,会重叠,且取大的那个,例子中1个10,一个20,取20

  html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title></title> 
<style>
*{
    margin:0;
    padding:0px;
    }
.divcss
{ 
    background-color:red;
    margin:10px;
} 
.divcss1
{ 
    background-color:green;
    margin:20px;
}
</style>
</head>
<body>
<div class="divcss"> 
 我是盒子1
</div>
<div class="divcss1"> 
我是盒子2
</div> 
</body>
</html>

  运行结果:

  第一个盒子

  

   第二个盒子:

  Body盒子:

原文地址:https://www.cnblogs.com/shawnhu/p/8138256.html