首页 > 解决方案 > 对所有可调整大小的子元素强制使用 flex 容器的最大宽度

问题描述

给定一个具有 2 列的固定大小的flex 容器:

  1. 一个左侧基于内容的动态宽度列;
  2. 一个可调整大小(双向)的普通文本区域。

textarea当用户调整大小(在两个方向上)时,我想控制宽度。

如何将容器的max-width大小强制为textarea(没有 javascript 和/或禁用水平调整大小),就好像它textarea是容器的直接子级一样?

我发现的唯一可行的纯 CSS 解决方案display: contents.right-content列上,不幸的是,并非所有浏览器都支持

.container {
  max-width: 100px;
  background-color: red;
  display: flex;
}

.left-content {
  background-color: yellow;
}

.right-content {
  display: contents;
}
<div class="container">
  <div class="left-content">foo</div>
  <div class="right-content">
     <textarea>bar</textarea>
  </div>
</div>

标签: htmlcssflexbox

解决方案


只需执行以下操作:

.container {
  max-width: 100px;
  background-color: red;
  display: flex;
}

.left-content {
  background-color: yellow;
}
.right-content {
  min-width:0; /* this will prevent the element from growing more than the flex container
                  related: https://stackoverflow.com/q/36247140/8620333*/
}

textarea {
  max-width:100%; /* this will prevent the text area from growing more than its parent*/
  display:block;  /* this will remove the whitespace from the bottom*/
  box-sizing:border-box; /* don't forget this*/

  opacity:0.8; /* to illustrate */
}
<div class="container">
  <div class="left-content">foo</div>
  <div class="right-content">
     <textarea>bar</textarea>
  </div>
</div>


推荐阅读