button, a {
height: 30px;
display: inline-block;
border: 1px solid black;
vertical-align: middle;
}
button > div, a > div {
width: 30px;
height: 10px;
background-color: red;
}
<button>
<div class="buttonDiv"></div>
</button>
<a href="#">
<div class="anchorDiv"></div>
</a>
We have buttons with icons in our project that render as button or anchor depending on props. We stumbled upon a problem with misalignment of button contents. In code snippet there is example.
Why does inner div
aligns differently in button and anchor? How do I align contents of button vertically correctly? I could have just added padding-top
but it does not seem right.
I'm afraid the reason you don't have a natural expected behaviour is that it's not valid HTML (as per HTML5) to include a div
inside of a button
. This means each browser may have a different way of rendering this.
As you said, you can do a workaround with padding or positioning easily to make it work as you desire, but it still won't be valid HTML. A possible workaround solution would be to reset paddings (to override default stylings) and vertically center content (without depending on the height of the element itself) on the anchor tag. https://jsfiddle.net/ne037nL7/
The button can only contain phrasing content which not only includes plain text but also span
, i
, and more (full list here https://www.w3.org/TR/2012/WD-html5-20120329/content-models.html#phrasing-content).
Source: W3 https://www.w3.org/TR/2012/WD-html5-20120329/the-button-element.html#the-button-element