当前位置: 移动技术网 > IT编程>网页制作>CSS > 相邻元素margin的自动合并与float的坑

相邻元素margin的自动合并与float的坑

2020年05月02日  | 移动技术网IT编程  | 我要评论

老虎机定位器,微信公共账号,第二次仙魔大战

css中相邻元素的margin其实是会自动合并的,且取较大值。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <style>
            .div1 {
                width: 60px;
                height: 60px;
                background-color: #fdd;
                border: 10px solid #fee;
                padding: 20px;
                margin: 30px;
                /*设置上下margin为30px*/
            }
            .div2 {
                width: 60px;
                height: 60px;
                background-color: #fdd;
                border: 10px solid #fee;
                padding: 20px;
                margin: 60px 30px;
                /*设置上下margin为60px*/
            }
        </style>
    </head>
    <body>
        <div class="div1"></div>
        <div class="div2"></div>
    </body>
</html>

实际效果:div1和div2上下相距60px,而不是90px。

那float的坑是什么啦?

那就是float会取消相邻元素margin的自动合并!

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <style>
            div {
                width: 60px;
                height: 60px;
                background-color: #fdd;
                border: 10px solid #fee;
                padding: 20px;
                margin: 30px;
                float: left;
                /*设置左浮动*/
            }
        </style>
    </head>
    <body>
        <div></div>
        <div></div>
    </body>
</html>

效果如下:两个div左右相距60px,而不是30px了!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网