【CSS】margin和padding理解

  W3C组织建议把所有网页上的对像都放 在一个盒(box)中,设计师可以通过创建定义来控制这个盒的属性,这些对像包括段落、列表、标题、图片以及层。

盒模型主要定义四个区域:内容 (content)、边框距(padding)即内边距、边界(border)和外边距(margin)。 对于初学者,经常会搞不清楚margin,background-color,background- image,padding,content,border之间的层次、关系和相互影响。这里提供一张盒模型的平面示意图,希望便于你的理解和记忆。

 

margin和padding属性:

1. Margin: 包括margin-top, margin-right, margin-bottom, margin-left, 控制块级元素之间的距离, 它们是透明不可见的, 对于Fig. 2所示的上右下左margin值均为40px, 因此代码为:

margin-top: 40px;
margin-right: 40px;
margin-bottom: 40px;
margin-left: 40px;

根据上, 右, 下, 左的顺时针规则, 简写为

margin: 40px 40px 40px 40px;

当上下, 左右margin值分别一致, 可简写为:

margin: 40px 40px;

前一个40px代表上下margin值, 后一个40px代表左右margin值.

当上下左右margin值均一致, 可简写为:

margin: 40px;

2. Padding: 包括padding-top, padding-right, padding-bottom, padding-left, 控制块级元素内部, content与border之间的距离, 其代码, 简写请参考margin属性的写法.

浏览器默认的marginpadding不同。解决方案是加一个全局的*{margin:0;padding:0;}来统一。

代码示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
    <head>  
        <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />  
        <style type="text/css">  
            body{  
                margin:0px;  
            }  
  
            .test1{  
                width:150px;  
                height:150px;  
                border:6px solid red;  
            }  
  
            .test2{  
                margin-top:40px;  
                padding-top:40px;  
                width:150px;  
                height:150px;  
                border:6px solid gray;  
            }  
  
            .test2_son{  
                width:80px;  
                height:50px;  
                border:12px solid blue;  
            }  
        </style>  
    </head>  
    <body>  
        <div class="test1">test1</div>  
        <div class="test2">  
            <div class="test2_son">test2_son</div>  
        </div>  
    </body>  
</html>  
View Code

 

说明:中灰色地带是class值为test2的div的边框,它是有宽度的;

①、内边距和外边距是针对于其作用的元素和其他元素来讲的,某一元素的内边距在另一个元素看来有可能是外边距,比如:class值为test2 div的内边距在class值为test2_test div元素看来就是外边距,

所以上面代码也可以这样写:将class值为test2的div样式列表中“padding-top:40px;”去掉,class值为test2_test div元素添加“margin-top:40px;”——这样的效果和代码2-1是一样的;

 


posted @ 2015-08-30 17:41  peterYong  阅读(377)  评论(0编辑  收藏  举报