margin的用法

margin的塌陷问题

    元素和元素在垂直方向上 margin 是有坑的.
css

示例 : html

html 结构 : 布局

<div class="father">
    <div class="box1"></div>        
    <div class="box2"></div>
</div>

 css 结构 : spa

       *{
            padding: 0;
            margin: 0;
        }
        .father{
            width: 400px;
            overflow: hidden;
            border: 1px solid gray;
        }
        .box1{
            width: 300px;
            height: 200px;
            background-color: red;
            margin-bottom: 20px;}
        .box2{
            width: 400px;
            height: 300px;
            background-color: green;
            margin-top: 50px;
        }

 

       效果 : code

  当给两个标准流下兄弟盒子 设置垂直方向上的margin时,那么以较大的为准,那么咱们称这种现象叫塌陷。无法解决,咱们称为这种技巧叫“奇淫技巧”。记住这种现象,在布局垂直方向盒子的时候主要margin的用法。htm

  当咱们给两个标准流下的兄弟盒子设置浮动以后,就不会出现margin塌陷的问题。blog

margin: 0 auto;     盒子居中

      div{
            width: 780px;
            height: 50px;
            background-color: red;
            /*水平居中盒子*/
            margin: 0px auto;
                        /*水平居中文字*/
            text-align: center;

        }

  当一个div元素设置margin:0 auto;时就会居中盒子,那咱们知道margin:0 auto;表示上下外边距离为0,左右为auto的距离,那么auto是什么意思呢?io

  设置margin-left:auto;咱们发现盒子尽量大的右边有很大的距离,没有什么意义。当设置margin-right:auto;咱们发现盒子尽量大的左边有很大的距离。当两条语句并存的时候,咱们发现盒子尽量大的左右两边有很大的距离。此时咱们就发现盒子居中了。class

另外如何给盒子设置浮动,那么margin:0 auto失效。技巧

 

使用margin:0 auto;注意点:

1.使用margin: 0 auto;水平居中盒子必须有width,要有明确width,文字水平居中使用text-align: center;

2.只有标准流下的盒子 才能使用margin:0 auto; 

当一个盒子浮动了,固定定位,绝对定位(后面会讲),margin:0 auto; 不能用了

3.margin:0 auto;居中盒子。而不是居中文本,文字水平居中使用text-align: center;

 

另外你们必定要知道margin属性是描述兄弟盒子的关系,而padding描述的是父子盒子的关系

善于使用父亲的 padding,而不是 margin

     

   代码 : 

        *{
            padding: 0;
            margin: 0;
        }
        .father{
            width: 300px;
            height: 300px;
            background-color: blue;
        }
        .xiongda{
            width: 100px;
            height: 100px;
            background-color: orange;
            
            margin-top: 30px;
        }

 

由于父亲没有border,那么儿子margin-top实际上踹的是“流” 踹的是行,因此父亲掉下来了,一旦给父亲一个border发现就行了。

那么问题来了,咱们不可能在页面中平白无故的去给盒子加一个border,因此此时的解决方案只有一种。就是使用父亲的padding。让子盒子挤下来。