About the box-sizing Attribute-writing in front of the cloud on a daily basis
If you have any mistakes or shortcomings in this article, you are welcome to criticize them and share them with us!
A problem occurs when writing css components in the project:
The two buttons are required to evenly share the width of the parent element, and the width of the parent element is not fixed, as shown in the following figure:
The first reaction was naturally to use the flex layout, but because it was compatible with ie9 and later, and the android x5 browser, and the layout of only two buttons was relatively simple, the floating method was selected:
Prompt information
OK
Cancel
.mask{ ...}.confirm{ ...}.confirm-text{ ... clear: both;}.confirm-btn{ float: left; width: 50%; ...}
But the problem arises. Add a border on the side of the button, and the branch is displayed. This problem can be solved if the width of each button is only 49% or even 49.5%, but it can still be found when you click to change the background color, and it is very ugly, in this case, you can use box-sizing: border-box to make the width of the element border be included in the width of the element itself. The problem is solved:
.confirm-btn{ box-sizing: border-box; float: left; width: 50%; ...}.confirm-btn:active{ background: rgb(235,235,235);}.confirm-btn-sure{ border-right: 1px solid rgb(235,235,235);}
The following describes the box-sizing attribute.
Box-sizing attributes
Box, as we all know, is the smallest unit in css layout. All the la s are built by a box with a rectangle, just like building blocks. Each box is composed of four parts, including content, padding, border, and margin. How is the box height and width calculated? In css, there is an attribute named box-sizing. Different values of this attribute determine the calculation method of box width and height.
First, let's talk about compatibility. Currently, IE9 and later versions and other modern browsers are tested to be compatible with this attribute.
This attribute has three optional values: content-box, padding-box, and border-box. The default value is content-box, but the compatibility of padding-box seems to be faulty, the latest version of chrome and safari does not take effect, so this article will not discuss it for the time being.
1. content-box (default)
This is the most common calculation method. The height of a box is equal to its height + padding + border + margin. The same is true for width.
2. border-box
When the value is border-box, the height of the box is equal to its height + margin. That is to say, the height of the box is composed of the height of the content, the padding, and the border, in other words, padding and border are not extended, but crowded inside.
.border-box{ box-sizing: border-box; width: 200px; height: 200px; padding: 50px;}