margin-top负值时和margin-bottom的区别

相信能看到这篇文章的都是跟我一样脑子时不时糊了的

现记录如下,防止以后再糊住

在CSS常用的垂直居中的方法中其中有一个方法就是利用了margin-top

代码如下:

    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .content {
            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative;
            top: 50%; /*偏移*/
            margin-top: -150px;
        }
    </style>

    <div class="content"></div>

注意:这里的position只能是 relative,不能是absolute,因为使用绝对定位absolute后,margin:0 auto居中方法会失效,(只有relative不会脱离文档流)这个时候同样需要使用margin-left负值方法来实现居中。

效果如下:毫无疑问实现了垂直方向的居中

这个时候就有同学说了还让margin-top为负值,费那个劲干嘛,直接margin-bottom为150px即可,代码如下:

margin-bottom: 150px; 
/* margin-top: -150px; */

效果如下:

醒醒了:margin-top的值如果为负的,就是向上移动,而如果用margin-bottom,盒子的上边不会动,只不过是在下方多“顶出来”150px的空白,又因为下边本来就是空白的,所以看起来margin-bottom就像是没有效果的也就是不会发生移动。(实际商由于多出来150px空白,屏幕右侧多出了滚动条)

这两种区别在top为0的时候效果会更明显:

margin-top:-150px效果如下

margin-bottom:150px效果如下

可以的看到margin-top为负值的时候盒子向上移动只剩下一半了,而margin-bottom是没有可见效果的。

补充:margin负值问题

margin-top 和 margin-left 负值,元素向上、向左移动

margin-right 负值,右侧元素左移,自身不受影响

margin-bottom 负值,下方元素上移,自身不受影响

猜你喜欢

转载自blog.csdn.net/a1059526327/article/details/109746537