Home > Enterprise >  Why box-sizing property act like this?
Why box-sizing property act like this?

Time:01-30

I want to create a 3x3 layout. I apply box-sizing: border-box to all the elements. It's pretty simple, but when I add borders on parent and child divs, the layout breaks.

html{
   box-sizing: border-box;
}
*{
   box-sizing: inherit;
}
.box{
      width: 300px;
      height: 300px;
      margin: 50px auto;
      border: 1px solid black;
    }
    .inner-box{
      height: 100px;
      width: 100px;
      background: cadetblue;
      border: 1px solid red;
      box-sizing: border-box;  
      float: left;
    }

Before I comment HTML and *

So to make it works, I have to comment styles for HTML and *. After that, the layout looks like this: After I comment HTML and *

I know I can set width on child elements to be calc(100%/3), but in that case, the width of child elements will be less than 100px. I'm curious why this happening and am I making some mistakes?

here is the HTML :

<div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
  </div>

CodePudding user response:

By using box-sizing: border-box, the outside box has an overall width of 300px - including its borders.

Hence there isn't quite enough space to get the third element in.

If you put the box-sizing of the outer box back to content then there is space:

html {
  box-sizing: border-box;
}

* {
  box-sizing: inherit;
}

.box {
  width: 300px;
  height: 300px;
  margin: 50px auto;
  border: 1px solid black;
  box-sizing: content-box;
}

.inner-box {
  height: 100px;
  width: 100px;
  background: cadetblue;
  border: 1px solid red;
  box-sizing: border-box;
  float: left;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

  •  Tags:  
  • Related