What exactly does the CSS box-sizing property change?

foreword

We all know that box-sizingattributes can limit the width and height of elements to make them 'introverted'. So do you know box-sizingwhat values ​​the attribute has? Do the corresponding values ​​represent those meanings? Next, I will take you to find out.

box model

To understand box-sizingattributes, we must first understand the structure of the box model.

A box model is made up of four 'inner boxes'.

They are, from inside to outside content box, , padding box, border boxand margin box.

The structure diagram is shown in the figure below:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-w0uzhctA-1660809047503)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /4ac136a19a504e769f353bacfb87968c~tplv-k3u1fbpfcp-watermark.image?)]

Seeing this, I think everyone understands more than half of it, yes:

These boxes correspond to contentthe , padding, borderand marginattributes, respectively.

box-sizingAttributes

box-sizingWhat the attribute actually changes is which box the width( height) attribute acts on.

For example, if an element is set, box-sizing: border-box;it means that widththe attribute acts on the border box.

The padding box box and the border box box are included in the border box box , so the width will not increase when we add the sum padding, borderwhich is 'introverted'.

When the property is not set box-sizing, its default value is box-sizing: content-box;

In other words, by default, widthit acts content boxon , so when we paddingset the sum border, the width will increase.

insert image description here

box-sizingattribute value

box-sizingThe value of an attribute can theoretically be written in the following ways:

    .box1 { 
        box-sizing: content-box; 
    } 
    .box2 { 
        box-sizing: padding-box; 
    } 
    .box3 { 
        box-sizing: border-box; 
    } 
    .box4 { 
        box-sizing: margin-box; 
    } 

In fact, the support situation is really like this:

     /* 默认值 */ 
    .box1 { 
        box-sizing: content-box; 
    }
    /* Firefox 曾经支持 */ 
    .box2 { 
        box-sizing: padding-box; 
    } 
    /* 全线支持 */
    .box3 { 
        box-sizing: border-box; 
    }  
    /* 从未支持过 */
    .box4 { 
        box-sizing: margin-box; 
    } 

box-sizing: padding-box;And box-sizing: margin-box;because the usage scenarios are limited, it does not support the use of .

Among them, box-sizing: padding-box;only the Firefox browser used to support it, and it has not been supported since version 50.

epilogue

This is the end of this article

If you have any other ideas, welcome to communicate in the comment area!

Guess you like

Origin blog.csdn.net/m0_47901007/article/details/126407534