这个文本区域周围的额外 space 在哪里?

Where is the extra space coming from around this textarea?

我的 textarea 遇到了一个奇怪的问题,即使在删除所有样式后,我的 textarea 周围仍然有剩余的 space。

在下面的示例中,我从文本区域中删除了除默认 2px padding 之外的所有样式。 active/focus 上的填充更改为 0px,但您仍然可以看到 space 的 1px

我试过了:

但无济于事..


问题

额外的 pixel/space 从哪里来?


演示:

.container {
  height: 200px;
  width: 500px;
  background: steelblue;
}

textarea {
  resize: none;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 2px; /* textarea default padding */
  border: 1px solid red;
  overflow: auto;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  border-radius: 0;
  background: rgba(255, 255, 255, 0.5);
}

textarea:focus,
textarea:active {
  outline: none;
  padding: 0;
}
<div class="container">
  <textarea></textarea>
</div>

只需在 textarea

中添加 box-sizing: border-box;
textarea {
  resize: none;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 2px; /* textarea default padding */
  border: 1px solid red;
  overflow: auto;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  border-radius: 0;
  background: rgba(255, 255, 255, 0.5);
  box-sizing: border-box; // Added
}

您的 textarea 宽度大于 container:100% + 2px 边框 + 2px 左填充 + 2px 右填充

所以在textarea中使用了box-sizing: border-box;

box-sizing 属性 允许我们在元素的总宽度和高度中包含填充和边框。

.container {
  height: 200px;
  width: 500px;
  background: steelblue;
}

textarea {
  resize: none;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 2px; /* textarea default padding */
  border: 1px solid red;
  overflow: auto;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  border-radius: 0;
  background: rgba(255, 255, 255, 0.5);
  box-sizing: border-box;
}

textarea:focus,
textarea:active {
  outline: none;
  padding: 0;
}
<div class="container">
  <textarea></textarea>
</div>

您需要在文本区域或所有元素中使用box-sizing: border-box;。我的建议用于所有元素。

By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added.

* {
  box-sizing: border-box;
}
.container {
  height: 200px;
  width: 500px;
  background: steelblue;
}

textarea {
  resize: none;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 2px; /* textarea default padding */
  border: 1px solid red;
  overflow: auto;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  border-radius: 0;
  background: rgba(255, 255, 255, 0.5);
}

textarea:focus,
textarea:active {
  outline: none;
  padding: 0;
}
<div class="container">
  <textarea></textarea>
</div>