Reputation: 6378
Was a bit confused when the next HTML code
<div>Some text insize DIV</div>
<textarea>Some text insize TEXTAREA</textarea>
with CSS
div {
background-color: #eee;
width: 25em;
}
textarea {
width: 25em;
}
displayed DIV and TEXTAREA with the different width... what is the reason?
JSFiddle example here
Upvotes: 1
Views: 54
Reputation: 8660
It's because those two elements have different default font-size
properties and the em
unit is based on the default font-size of whatever element you assign it to.
Here's a fiddle that shows the difference:
https://jsfiddle.net/j985xpmq/1/
Here's a fiddle that shows them the same:
https://jsfiddle.net/j985xpmq/4/
You'll notice that I removed padding from the textarea
and added a border to the div
Upvotes: 2
Reputation: 22760
To further prove zfrisch's correct answer, this is almost equal:
div {
background-color: #eee;
width: 25em;
font-size:14px;
}
textarea {
width: 25em;
font-size:14px;
}
Where the default font-scaling is maintained the same for each element, and the <textarea>
box also features default padding so is still a very slightly different size from the div width, but they are very close now.
https://jsfiddle.net/j985xpmq/3/
Upvotes: 1
Reputation: 43698
em
s are a measured based on the font-size
and each of those elements have a different font size. The div
is font-size: 16px
and the textarea
is font-size: 11px
at least as a default in Chrome.
If you set the elements to the same font-size
then they will be almost the same width. The remaining difference is because the textarea
has padding and border too.
If you set the CSS to this, then the elements will be the same size:
div {
background-color: #eee;
width: 25em;
font-size: 16px;
box-sizing: border-box;
}
textarea {
width: 25em;
font-size: 16px;
box-sizing: border-box;
}
because they will both have the same font-size, and the widths will be based on the border-box instead of the content-box, so padding and borders will be included in the width.
References:
Upvotes: 2