Horen Horen - 1 year ago 143
CSS Question

Vertical align between div and input

I am trying to vertically align a

and an

<div id="a">
<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:


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
. I want to understand why the vertical-align behaves this way and try to find a clean solution.

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download