当文本区域位于网格容器中时如何使 cols="" 工作

How to make cols="" work when a textarea is in a grid container

当 Chrome 和 Firefox 位于网格容器中时,它们似乎都不尊重 textarea 元素上的 cols 属性:

.grid { display: grid; }

textarea:not([cols]) { width: 100%; }
<h2>Not in a grid container:</h2>

<div>
  <textarea cols="10" rows="6">some dummy text</textarea>
  <textarea>some other text</textarea>
</div>

<h2>In a grid container:</h2>

<div class="grid">
  <textarea cols="10" rows="6">some dummy text</textarea>
  <textarea>some other text</textarea>
</div>

rows 属性如我所料受到尊重。

我需要一个 texarea 网格容器内时尊重 cols,如果 cols 不存在,则取 100%可用宽度。

你需要带一个块元素父元素来修复它。

.grid {
  display: grid;
}

textarea:not([cols]) {
  width: 100%;
}
<h2>Not in a grid container:</h2>

<div>
  <textarea cols="10" rows="6">some dummy text</textarea>
  <textarea>some other text</textarea>
</div>

<h2>In a grid container:</h2>

<div class="grid">
  <div>
    <textarea cols="10" rows="10">some dummy text</textarea>
  </div>
  <textarea>some other text</textarea>
</div>

这是一个对齐问题,导致文本区域在默认情况下被拉伸。您可以使用右边的 margin auto

来解决这个问题

.grid { display: grid; }

textarea:not([cols]) { width: 100%; }

textarea {
  margin-right:auto;
}
<h2>Not in a grid container:</h2>

<div>
  <textarea cols="10" rows="6">some dummy text</textarea>
  <textarea>some other text</textarea>
</div>

<h2>In a grid container:</h2>

<div class="grid">
  <textarea cols="10" rows="6">some dummy text</textarea>
  <textarea>some other text</textarea>
</div>