有没有一种方法可以指定边框的相对宽度和最小内容宽度?

时间:2020-05-27 03:37:54

标签: html css

是否可以将不同的盒装尺寸应用于不同的宽度规格?可以将最小宽度指定为使用content-box,将%宽度指定为使用border-box,还是将box-sizing应用于元素上的所有宽度规格?

td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  /* including padding and border */
  width: 100%;
  /* based on content only */
  min-width: 2em;
  /* box-sizing: border-box; */
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}
<table>
  <tr>
    <th>
      <div>Content that increases the width of the column</div>
    </th>
    <th>
      <div>...
        <!-- content less than the desired minimum width of the input element -->
      </div>
    </th>
  </tr>
  <tr>
    <td><input type="text" value="42" /></td>
    <td><input type="text" value="42" /></td>
  </tr>
</table>

在这种特殊情况下,输入应填充列的宽度而不会超出范围。取消对框大小的注释可以解决此问题,但是会使输入的内容空间小于所需的最小宽度。

1 个答案:

答案 0 :(得分:0)

这是到目前为止我开发的JavaScript解决方案:

$("[style*='min-width']").each(function(ndx, elem) {
    $elem = $(elem);
    $elem.css("min-width", parseInt($elem.css("min-width").slice(0, -2)) + $(elem).outerWidth() - $(elem).width() + "px");
})
td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  width: 100%;
  /* including padding and border */
  box-sizing: border-box;
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
  <tr>
    <th>
      <div>Content that increases the width of the column</div>
    </th>
    <th>
      <div>...
        <!-- content less than the desired minimum width of the input element -->
      </div>
    </th>
  </tr>
  <tr>
    <td><input type="text" value="42" style="min-width: 2em;" /></td>
    <td><input type="text" value="42" style="min-width: 2em;" /></td>
  </tr>
</table>