Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical-align baseline not working

Tags:

html

css

I have a very simple setup:

<button>
    Lorem
</button>
<input type="text" value="Ipsum">

with both elements next to each other using display: inline-block:

button, input{
    height: 34px;
    line-height: 34px;
    display: inline-block;
    box-sizing: border-box;
    vertical-align: baseline;
    padding: 0;
    margin: 0;
    border: 1px solid green;
    font-size: 14px;
}

Example here: http://jsfiddle.net/j02ypo0v/

enter image description here

As you can see, the two elements are not perfectly aligned (off 1px).

I know, I could easily solve this by changing vertical-align to middle, but I want to understand why this offset is present in the first place.
IMO, it doesn't make any sense that the two elements are not perfectly vertically aligned since they share all CSS attributes (especially height, line-height, display and vertical-align).

Can anybody explain me where the 1px offset is coming from?

like image 842
Horen Avatar asked Sep 28 '15 14:09

Horen


People also ask

What is vertical-align baseline?

Defines how an inline or table-cell element aligns vertically. vertical-align: baseline; The element is aligned with the baseline of the parent. Some text before some text after.

How does vertical-align work?

The vertical-align property in CSS controls how elements set next to each other on a line are lined up. In order for this to work, the elements need to be set along a baseline. As in, inline (e.g. <span> , <img> ) or inline-block (e.g. as set by the display property) elements.

Is vertical-align deprecated?

Deprecated as an attribute Occasionally you will see “valign” used on table cells to accomplish vertical alignment. e.g. <td valign=top> . It should be noted that this attribute is deprecated and should not be used.


1 Answers

The baseline alignment is to do with the positioning of the text rather than the positioning of the element as a whole. If we zoom in on the button and input elements and add a straight line below the text, you'll see that the text in both elements is in fact vertically aligned at the same position:

Example

I can't tell you what the exact cause of the problem is, but what I do know is that if you reduce the line-height to 32px or increase it to 35px the two elements become in line with each other whilst keeping the text in line as well:

Example 2

My guess is that there's a difference in calculation on the browser side of things when using a line-height of 34px and a font-size of 14px between a button and input element as in your example, as if we do change the vertical-align to middle as your question suggests the text is no longer in line:

Example 3

like image 164
James Donnelly Avatar answered Sep 30 '22 20:09

James Donnelly