Horen Horen - 27 days ago 17
CSS Question

Vertical align between div and input

I am trying to vertically align a

div
and an
input
:

<div id="a">
Button
</div>
<input type="text" id="b" placeholder="text">


They both share the same styles:

#a, #b{
box-sizing: border-box;
vertical-align: baseline;
padding: 0;
margin: 0;
outline: none;
font-size: 10px;
line-height: 10px;
font-family: serif;
border: none;
height: 30px;
width: 100px;
background: green;
display: inline-block;
border: none;
}


However, they are not vertically aligned:

Sample

How is that possible?

Please note: This is an abbreviated example from a bigger project where I have to use
vertical-align: baseline
. It is not possible to change that value and I do not want to use any hack like adding a
margin-top
. I want to understand why the vertical-align behaves this way and try to find a clean solution.

Answer

Since your height has a static value, you can use line-height: 30px; CSS property to force the alignment you want.

JSFiddle

Cumbersome explanation:

Your div's baseline is 10 px (see line-height property), while your element's height is 30 px. Text inside input element is vertically centered by default, baseline, in your case, 30px. So basically, browser tries to center elements by it's baseline, which is different for the elements, thus causing the first element, with a smaller baseline value, to be pushed down.

Comments