文本区下的额外空间,因浏览器不同而不同

在 textarea 标签下有一些额外的空间。在不同的浏览器中,从1到4像素不等。标记非常简单:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


<html>
<head>
<style>
body {
margin: 0;
padding: 0;
}
.main {
background-color: red;
}
textarea {
background-color: gray;
resize: none;
margin: 0;
border: 0 none;
padding: 10px;
height: 50px;
overflow: hidden;
}
</style>
</head>
<body>
<div class="main">
<textarea></textarea>
</div>
</body>
</html>

以下是它在浏览器中的呈现方式:

Screenshot

为什么会发生这种情况? 如何消除这个额外的空间?

18066 次浏览

Add vertical-align: top to textarea.

The reason for the gap is that textarea is an inline (or inline-block) element, and the gap is the space reserved for descenders in text. I don't know exactly why the gap is different between different browsers.

In my case, thirtydot's answer didn't work well with the parent <div>'s bottom border.

display: block suited me nicely though.

I also found that the space goes away if the textarea's parent is using display:flex:

/* The relevant part: */
#FlexLayout { display: flex; flex-direction: column; }


/* The boring part: */
.ShowChildBorders * { border: 1px solid; }
#DefaultLayout * { border-color: red; }
#FlexLayout * { border-color: green; }
#SideBySide { display: flex; }
#SideBySide > div { flex: 1; margin: 4px; }
#SideBySide * { margin: 0; padding: 0; }
<div id="SideBySide">
<div class="ShowChildBorders">
<div id="DefaultLayout">
<div>Default Layout</div>
<textarea>Text Area</textarea><br/>
<textarea>Text Area</textarea>
</div>
</div>
<div class="ShowChildBorders">
<div id="FlexLayout">
<div>Flexbox Layout</div>
<textarea>Text Area</textarea>
<textarea>Text Area</textarea>
</div>
</div>
</div>

On Chrome 91.0.4472.77, Windows 10 64-bit, that renders as:

enter image description here