简体   繁体   中英

Applying width to flex item, same value as flex-basis, causes spacing changes

I noticed some strange behavior in a web project of mine. I've recreated similar behavior in a codepen to demonstrate:

The summary is:

  • I have a flex item specified as: flex: 0 0 170px;
  • Devtools shows its computed value as 170px (as expected).
  • If I add an additional css property of "width: 170px", some spacing of other elements in the dom changes.

I would expect setting this property to have no effect, but that's not the case.

Here's the codepen: https://codepen.io/benrhere/pen/BaPKRQd

This image shows that we're dealing with a computed width of 170px for the div in question (with an X) 显示计算选项卡的图像

This shows that, before I set the width property on that div, we see spacing as shown. 设置宽度属性前的图像

After I set the width property for that div (to the same width as the flex-basis, and to the same value as was computed), some spacing overall in the dom shrinks. 设置宽度属性后的图像

Very curious for any thoughts on why this is having any effect at all. Thank you.

Edit: For refernce, this repros on Chrome Version 108.0.5359.125 (Official Build) (64-bit), Windows 11. Not sure about other environments.

Writing my comment as an anwser for clearer text:

  • #rightContainer with a 170px child element takes up its full max-width: 320px
  • and consumes an additional margin: 2% from #outerFlex

This leaves 700px - 326.4 = 373.6px minus a few border = 364px for #nestedFlex to distribute two columns of 170px with space-evenly.

  • 364px - 2 * 170px - 4 * 1px border = 20px to create even spacing around the child elements.
  • divided by 3 = ~7px of space between and outside the child elements.

Without the .rightPosObj child element #rightContainer will only take up its min-width: 300px giving #rightContainer 20px additional pixels to space evenly. Basically (20px + 20px) / 3 = ~13px between and outside the child elements.

Hense the tiny shift in spacing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM