About elements of box-sizing property

CSS problem (box-sizing property) border width and height of the impact element

problem

We in the page layout with CSS, often give the elements specified width and height. In the absence of a border (border to 0) tends to width and height of parent element is a child element wide and high. But after adding a border width If you do not adjust the width of the element can lead to confusion layout.

For example, we want to do the following effects:

There are three sub-elements of a width of the parent element 200px 600px lower.

It can be achieved:

<body>
    <div class="container"> <div class="item one"></div> <div class="item two"></div> <div class="item three"></div> </div> </body>
.container{
    width: 600px; height: 400px; display: flex; flex-wrap: wrap; background-color: blue; } .item{ width: 200px; height: 400px; } .one{ background-color: #bbb; } .two{ background-color: #777; } .three{ background-color: #444; } 

 

But if add a border:

.item{
    width: 200px; height: 400px; border: 2px solid red; } 

 

This happens:

the cause of this situation is that the width of the border is not within the range of elements 200px, when actually increase the width of the element border becomes a 204px (200 + 2 + 2) . The width of the parent element of this will be enough to cause a child element wrap.

solution

There are two options to solve this problem, the first element is modified in accordance with changes in the width and height attributes. (Of course not recommended, and newcomers do not understand the css will only do it ./* though I had done so * /)

The right solution is to modify the box-sizing property. The box-sizing to border-box can be.

.item{
    width: 200px; height: 400px; border: 2px solid red; box-sizing: border-box; } 

 

This achieves the effect we want, but do not need to modify the width and height of the element.

Guess you like

Origin www.cnblogs.com/KoBe-bk/p/11443203.html