Home > OS >  Why is the height of <form> more than the height of the <textarea> inside it?
Why is the height of <form> more than the height of the <textarea> inside it?

Time:08-22

Minimal example for my question:

console.log(document.getElementById('form').offsetHeight)
console.log(document.getElementById('textarea').offsetHeight)
form {
  background: orange;
}

textarea {
  background: lightblue;
  border: 0;
  box-sizing: border-box;
  height: 100px;
}
<form id="form"><textarea id="textarea"></textarea></form>

The <textarea> has a height of 100px but <form> has a height of 4px? Where is the extra 4px of height for the <textarea> coming from? How can I eliminate the extra height?

CodePudding user response:

A <textarea> is inherently a display-block (essentially adding a 'space').

Try adding display: block

form {
  background: orange;
  padding: 0;
}

textarea {
  padding: 0;
  margin: 0;
  display: block; 
  background: lightblue;
  height: 100px;
}
<form id="form"><textarea id="textarea"></textarea></form>

CodePudding user response:

I think it's because the textarea's display property is initially set as inline-block (see the Styling with CSS section). This stack overflow post's accepted answer provides a nice explanation of why it's displaying the additional "height" (that you're experiencing). According to the post, the following solutions seem to remedy the issue:

  1. set the display property to block or
  2. set the vertical-align property to top


With display: block:

form {
  background: orange;
  padding: 0;
}

textarea {
  padding: 0;
  margin: 0;
  background: lightblue;
  height: 100px;
  display: block; 
}
<form id="form"><textarea id="textarea"></textarea></form>


With vertical-align: top:

form {
  background: orange;
  padding: 0;
}

textarea {
  padding: 0;
  margin: 0;
  background: lightblue;
  height: 100px;
  vertical-align: top;
}
<form id="form"><textarea id="textarea"></textarea></form>

  • Related