I recently discovered that the text inside a <button>
is automatically vertically centered, whereas the text inside a <div>
is aligned to the top.
Despite my best efforts, I couldn't determine which CSS rule was responsible for this distinction.
div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
}
div {
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}
<div>text text</div>
<button>text text</button>
<div>text text text text</div>
<button>text text text text</button>
<div>text text text text text text</div>
<button>text text text text text text</button>
In the example provided above, after comparing all computed CSS rules in Chrome, I could only spot one difference - align-items: stretch
for <div>
and align-items: flex-start
for <button>
.
Even though assigning align-items: flex-start
didn't resolve the issue. This left me completely perplexed.
What baffles me is that the vertical text alignment differs between <div>
and <button>
even when all CSS rules are set with corresponding identical values. Essentially, with matching CSS rules, <div>
and <button>
behave dissimilarly. Why?
What is the underlying magic at play here?
I have managed to centralize the text vertically inside a <div>
(as seen below). However, I am simply intrigued by what causes the discrepancy in text alignment.
Perhaps it's not due to a specific CSS rule, but rather because the layout algorithms for these two elements differ within the browser?
div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
}
div { /* basic CSS rules to button-fy */
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}
/* Magic */
div, button {
vertical-align: middle;
}
div span {
display: inline-block;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
<div><span>text text</span></div>
<button>text text</button>
<div><span>text text text text</span></div>
<button>text text text text</button>
<div><span>text text text text text text</span></div>
<button>text text text text text text</button>