What is a box model

The browser renders the elements we write as boxes, and we modify the width, height, and other properties of the boxes using CSS. The calculation of the box from outside to inside is generally margin +border +padding +content.

Types of box models

Box models are mainly divided into two types, one is content-box and the other is border-box. We usually use the border-box.

Change box model

We control the type of box model by setting box-sizing values for elements using CSS.

  • Content-box, which is the default for box-sizing. If you set the width and height of an element (provided you can set the width and height), then you set the width and height of the content+paddinng+border area.
.box{
    width:100px;
    height:120px;
    margin:100px;
    padding:100px;
    border:10px;
}

Copy the code

So the actual width of the box =100+100+100+10+10=320px; Height =120+100+100+10+10=340px. Padiding +border+content.

  • Border-box, set this value to indicate that the box values are both padding and border, which makes it easier to layout.

Margin merge problem

The top and bottom margins of a block are sometimes merged (folded) into a single margin of the maximum size of a single margin (or only one of them if they are equal). This behavior is colloquially known as margin merging.

There are roughly three cases.

Between sibling elements

style{ .box1{ margin-bottom:50px; } .box2{ margin-top:50px; }}Copy the code

Normally we would assume that the margins of the two boxes would merge and become 100px. In real life, merging only picks large values and keeps them.

Between parent and child elements

Margin merge issues are also raised if parent and child elements are involved. And the overlap spills out of the parent element.

<style> .parernt { margin-top: 10px; margin-bottom: 10px; } .child1 { margin-top: 100px; } .child2 { margin-bottom: 100px; } </style> <div class="parent"> <div> Top edge overlaps 100</div> </div>Copy the code

Empty block-level elements

Margin merging triggers margin merging with other elements when a block-level element has no content but has a margin value set to none.