Search code examples
htmlcssvertical-alignment

Why does vertical-align: middle causes other elements to misalign?


With this code:

.header {
  background-color: #444;
  height: 56px;
  color: white;
}

a {
  padding: 20px;
}

input {
  background-color: #444;
  border: 0;
  line-height: 24px;
  margin-left: 10px;
  color: white;
  height: 56px;
  padding: 0;
  font-size: 20px;
  vertical-align: middle;
}
<div class="header">
  <a href="#">
    <img src="http://directoryapp.trimian.com/img/directory/ic_search_white.png" />
  </a>
  <input placeholder="Search" />
</div>

http://plnkr.co/edit/o6Gh6tARL7Kt1zxNHaFO?p=preview

bad alignment

Why is the image misaligned? If I remove the vertical-align: middle on the input the image lines up fine.

good alignment

In the chrome inspector the bounding box that is highlighed for the image also doesn't correspond to where it is rendered on the page (the bounding box is correct).

Am I designing the CSS for this header bar wrong?


Solution

  • Applying vertical-align to one element doesn't cause miss-alignment for another element.

    If you don't apply the vertical-align then both element (in your example) would be aligned same by the browser. Suppose if browser default is vertical-align: top; then both element is aligned to top. So, you see no miss-alignment between them. But when you use vertical-align: middle to one and leave default for another then browser default alignment and your alignment mismatch. So, you see miss-alignment between them.

    To conclude, use vertical-align on both element so that browser will render accordingly.