Html CSS Flexbox 问题:为什么我的 flexchildren 的宽度受其内容的影响?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7985021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:21:22  来源:igfitidea点击:

CSS Flexbox issue: Why is the width of my flexchildren affected by their contents?

htmlcssflexbox

提问by zakdances

The 2 children of my flexbox are each given a style of box-flex: 1. My understanding is that their widths should then be equal to each other(both occupying 50%of the total width of their parent flexbox). But when content is added to the children, their width changes (depending on what the content is and padding)! Why does this happen?

我的 flexbox 的 2 个孩子都被赋予了box-flex: 1. 我的理解是它们的宽度应该彼此相等(两者都占据其父 flexbox 总宽度的50%)。但是当内容添加到子项时,它们的宽度会发生变化(取决于内容和填充的内容)!为什么会发生这种情况?

CSS:

CSS:

.hasFlex {
   display: box;
   display: -webkit-box;
   display: -moz-box;
   -webkit-box-align: start;
   -moz-box-align: start;
   box-align: start;}
.box0 {
   -webkit-box-flex: 0;
   -moz-box-flex: 0;
   box-flex: 0;}
.box1 {
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  box-flex: 1;}
.box2 {
   -webkit-box-flex: 2;
   -moz-box-flex: 2;
   box-flex: 2;}
.box3 {
   -webkit-box-flex: 3;
   -moz-box-flex: 3;
   box-flex: 3;}
.container {
margin-bottom: 10px;
}

HTML:

HTML:

<div class="container hasFlex">
<div id="main" role="main" class="box1">
    <div class="innerBG">
      a bunch of stuff (divs, text, etc) go here
    </div>
</div>
<div id="sidebar" class="box1">
    <div class="innerBG">
       a bunch more stuff (divs, text, etc.) go here
    </div>
</div>
</div>

回答by thirtydot

The workaround for this is to add width: 0to the .box1elements.

解决方法是添加width: 0.box1元素中。

See:http://jsfiddle.net/thirtydot/fPfvN/

见:http : //jsfiddle.net/thirtydot/fPfvN/

I think I found that out for myself here: http://oli.jp/2011/css3-flexbox/

我想我在这里为自己找到了:http: //oli.jp/2011/css3-flexbox/

The preferred width of a box element child containing text content is currently the text without line breaks, leading to very unintuitive width and flex calculations → declare a width on a box element child with more than a few words (ever wonder why flexbox demos are all “1,2,3”?)

包含文本内容的框元素子元素的首选宽度目前是没有换行符的文本,导致非常不直观的宽度和 flex 计算 → 用多个单词在框元素子元素上声明宽度(有没有想过为什么 flexbox 演示都是“1,2,3”?)

Note that for your situation, it looks far easier to use display: table+ table-layout: fixed: http://jsfiddle.net/thirtydot/fPfvN/1/. Though, flexbox does allow you to quickly change things around in a way that display: tablecan't compete with.

请注意,对于您的情况,使用display: table+看起来要容易得多table-layout: fixedhttp: //jsfiddle.net/thirtydot/fPfvN/1/。尽管如此,flexbox 确实允许您以一种display: table无法与之竞争的方式快速改变事物。