You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让带colors类的Div被限制在Fieldset宽度内并显示横向滚动条?

解决方案

问题根源在于Flex容器的默认行为:.colors作为Flex行容器,默认min-width: auto,会被子元素总宽度撑大,进而导致父级容器和fieldset一同被拉长。只需修改.form .colors的CSS规则,添加min-width: 0打破默认行为,即可让颜色方块容器被限制在fieldset宽度内并显示横向滚动条。

修改后的完整代码

CSS

* {
  font-family: inherit;
  font-size: inherit;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  word-break: break-word;
}

html,
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: 1rem;
  width: 100%;
  height: 100%;
  padding: .25rem;
}

.hide {
  display: none !important;
}

.column {
  flex: 1;
  display: flex;
  flex-flow: column;
}

.row {
  flex: 1;
  display: flex;
  flex-flow: row;
}

.gap {
  gap: .25rem;
}

input,
textarea {
  flex: 1;
  border: 1px solid lightgray;
  border-radius: .25rem;
  padding: .5rem;
}

textarea {
  resize: none;
  min-height: 10rem;
}

.form {
  background-color: bisque;
  border: 1px solid lightgray;
  border-radius: .25rem;
  width: 100%;
  max-width: 62.5rem;
}

.form fieldset {
  border: none;
  padding: .5rem;
}

.form label {
  color: gray;
  font-size: small;
}

.form .colors {
  overflow-x: auto;
  min-width: 0; /* 核心修改:限制容器宽度不被子元素撑大 */
}

.colorBox {
  width: 150px;
  height: 150px;
}

.colorBox.yellow {
  background-color: yellow;
}

.colorBox.red {
  background-color: red;
}

.colorBox.green {
  background-color: green;
}

.colorBox.blue {
  background-color: blue;
}

HTML

<form action="#" class="form">
  <fieldset class="column gap">
    <div class="column">
      <label>Title</label>
      <input type="text" name="title">
    </div>
    <div class="column">
      <label>Details</label>
      <textarea name="details"></textarea>
    </div>
    <div class="column">
      <label>Colors</label>
      <div class="row gap colors">
        <div class="colorBox yellow"></div>
        <div class="colorBox red"></div>
        <div class="colorBox green"></div>
        <div class="colorBox blue"></div>
        <div class="colorBox yellow"></div>
        <div class="colorBox red"></div>
        <div class="colorBox green"></div>
        <div class="colorBox blue"></div>
      </div>
    </div>
  </fieldset>
</form>

原理说明

  • min-width: 0 覆盖了Flex容器默认的min-width: auto行为,允许容器宽度被压缩到父级的可用范围内,不再被子元素总宽度撑开。
  • 配合已设置的overflow-x: auto,当颜色方块总宽度超过容器宽度时,自动显示横向滚动条,同时fieldset和form的宽度会保持在设定的最大宽度内。

内容的提问来源于stack exchange,提问作者JorgeZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:55:14