The CSS box model collapses.

The reason for the collapse of the box model.

When the child element sets the outer margin, causing the parent element to go down, it will cause the box model to collapse.

For example the following situation.

    <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .btn{
    
    
            width: 100px;
            height: 100px;
            background-color: #53e1ff;
        }
        .obj{
    
    
            margin-top: 10px;
            width: 40px;
            height: 40px;
            background-color: #ff738e;
        }
    </style>
</head>
<body>
<div class="btn">
    <div class="obj"></div>
</div>

insert image description here
How to fix box model collapse.

  • Set the border in the parent element. border.
    <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .btn{
    
    
            width: 100px;
            height: 100px;
            background-color: #53e1ff;
            border: 1px solid red;//设置border
        }
        .obj{
    
    
            margin-top: 10px;
            width: 40px;
            height: 40px;
            background-color: #ff738e;
        }
    </style>
</head>
<body>
<div class="btn">
    <div class="obj"></div>
</div>

insert image description here

  • Sets the padding for the parent element. padding.
  <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .btn{
    
    
            width: 100px;
            height: 100px;
            background-color: #53e1ff;
            padding-top:10px ;设置padding
        }
        .obj{
    
    
            margin-top: 10px;
            width: 40px;
            height: 40px;
            background-color: #ff738e;
        }
    </style>
</head>
<body>
<div class="btn">
    <div class="obj"></div>
</div>

insert image description here

  • Add overflow hide to the parent element. overflow:hidden.
    <style>
        *{
    
    
            margin: 0;
            padding: 0;
        }
        .btn{
    
    
            width: 100px;
            height: 100px;
            background-color: #53e1ff;
            overflow: hidden;//添加溢出隐藏。
        }
        .obj{
    
    
            margin-top: 10px;
            width: 40px;
            height: 40px;
            background-color: #ff738e;
        }
    </style>
</head>
<body>
<div class="btn">
    <div class="obj"></div>
</div>

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46953330/article/details/114896193