Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

html - Why is padding expanding a flex item?

In the snippet below, the first row has two divs with flex-grow: 1. As expected, each div takes up 50% of the screen.

When adding padding to the left div, that is no longer the case. Can someone explain why?

body > div {
  height: 50px;
  display: flex;
}
body > div > div {
  flex: 1;
  box-sizing: border-box;
}
#a {
  background-color: red;
}
#b {
  background-color: green;
}
#c {
  padding: 10px;
  background-color: blue;
}
#d {
  background-color: yellow;
}
<div>
  <div id="a"></div>
  <div id="b"></div>
</div>
<div>
  <div id="c"></div>
  <div id="d"></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The calculations are defined in the spec.

A flex item's size with padding and flex-grow is determined by calculations in the flexbox spec.

These calculations are similar to the sizing of flex items with padding and flex-shrink.

Frankly, the math is quite technical and not the easiest thing in the world to understand.

But if you want to get into it, here are the details:


Examples

Below are examples that hopefully make the behavior more clear.

NOTE: Keep in mind that flex-grow is not a tool for directly establishing the length of a flex item. It's a tool for distributing space in the container among flex items. The flex-basis property sets the initial main size of a flex item. If flex-grow is used with flex-basis, the problem in the question is resolved (see example #4 below).

Example #1

In a block container, where you have box-sizing: border-box, the boxes in your code will render evenly regardless of padding.

body > div {
  height: 50px;
  /* display: flex; */
  font-size: 0; /* remove inline block whitespace */
}
body > div > div {
  /* flex: 1; */
  box-sizing: border-box;
  height: 50px;
  display: inline-block;
  width: 50%;
}
#a {
  background-color: red;
}
#b {
  background-color: green;
}
#c {
  padding: 10px;
  background-color: blue;
}
#d {
  background-color: yellow;
<div>
  <div id="a"></div>
  <div id="b"></div>
</div>
<div>
  <div id="c"></div>
  <div id="d"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...