欢迎来到夜的世界

莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生.料峭春风吹酒醒,微冷,山头斜照却相迎。回首向来萧瑟处,归去,也无风雨也无晴。
扩大
缩小

margin的用法

margin的塌陷问题

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

示例 : 

html 结构 : 

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

 css 结构 : 

       *{
            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;
        }

 

       效果 : 

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

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

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是什么意思呢?

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

另外如何给盒子设置浮动,那么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。让子盒子挤下来。

 

posted on 2018-09-21 16:46  二十四桥_明月夜  阅读(414)  评论(0)    收藏  举报

导航