忽略最大宽度的宽度(以像素为单位):100%

时间:2016-06-10 19:16:16

标签: html css css3 width flexbox

我在widthmax-width之间遇到问题,这个问题是在一个带有祖父母flex位置容器的元素中工作。

当我在此元素中使用带有width的像素max-width: 100%时,如果宽度大于其父级,则只会忽略max-width:100%。但是,例如,如果我使用width: 150%,则max-width:100%可以正常工作。



body{
  width: 640px;
  height: 360px;
  position: relative;
}
body:before{
  content:"";
  width:100%;
  height:100%;
  box-sizing: border-box;
  position: absolute;
  border: 2px solid black;
}
body:after{
  content:"16:9 screen size ratio example";
  position: absolute;
  bottom: 0;
  right: 10px;
}
#flex-container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: row nowrap;
  background-color: #95a5a6;
}
#sidebar{
  min-width:150px;
  flex: 0 1 150px;
  background-color: #7f8c8d;
}
#main-content{
  width:100%;
  flex: 1 1 auto;
  background-color: white;
}
.page{
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}
.grid{
  width: 800px;
  max-width: 100%;
  height: 200px;
  background-color: red;
  color: white;
  padding: 16px;
  box-sizing: border-box;
}

<div id="flex-container">
  <div id="sidebar"><h2>Sidebar</h2></div>
  <div id="main-content">
    <div class="page">
      <h1>Content page</h1>
      <div class="grid">
        A grid with certain width defined in units and based on the device. Specified width should not exceed its parent width (max-width: 100%).
      </div>
    </div>
  </div>
</div>


<br><br><br>


Should work like this:
<br>
<div style="width:640px;height:360px; border: 2px solid black;background-color:white;">
  <div style="width:100%;height:100%;">
    640px width parent
    <div style="max-width:100%; width:800px; height:100px; background-color:green;color:white;">
      800px width with max-width:100%
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

这是JSFiddle

1 个答案:

答案 0 :(得分:2)

您的容器(body)为width: 640px

body#flex-container)的孩子是width: 100%。换句话说,640px。

您的左侧隐藏项(#sidebar)为min-width: 150px。为了论证的缘故:width: 150px

您的右侧弹性项目(#main-content)是width: 100%。计算到:531.989px(原因tbd)。

#main-content.page)的孩子是width: 100%。另外,531.989px

.page.grid)的孩子是width: 500px。这非常适合父母,剩下额外的空间(31.989px)。

您的max-width: 100%从未见过任何动作。它有效,它没有被召唤。

在第二个示例中,您将width: 800px应用于.grid等效值,大于531.989像素,因此max-width: 100%将被调用。

Flex项目最小尺寸

请注意,默认情况下,弹性项目不会缩小超过其内容的大小。

min-width: 0添加到#main-content

说明:Why doesn't flex item shrink past content size?

语法错误

另请注意您的line commenting syntax ...

.grid {
  width: 500px; // For some reason this ignores max-width when is defined in units.
  max-width: 100%;
  height: 200px;
  background-color: red;
  color: white;
  padding: 16px;
  box-sizing: border-box;
}

....和parenthesis around the flex property ...

#sidebar{
  min-width:150px;
  flex(0, 1, 150px);
  background-color: #7f8c8d;
}
#main-content{
  width:100%;
  flex(1, 1, auto);
  background-color: white;
}

造成重大问题。

Revised Fiddle

相关问题