Search code examples
htmlcssvertical-alignment

line-height:0 puts the image in vertical center of button


I saw this code in other site, when I tried to center the img in a button vertically.

button {
  line-height: 0;
  height: 50px;
}
img {
  height: 25px;
}
<button>
  <img 
       src="https://www.materialui.co/materialIcons/action/search_24px.svg" 
       alt="search" />
</button>

Without line-height: 0; image is not exaclty verticaly center of the button. But when we put line-height: 0; it's gone perfect. I tested it in chrome 50. Why is this happening?

http://codepen.io/asim-coder/pen/ezmYwm


Solution

  • Why line-height: normal didn't worked because the value of "normal" is not just a single concrete value that is applied to all elements, but rather computes to a "reasonable" value depending on the font size set (or inherited) on the element. Height and line-height are two different things. That's why you didn't get vertically centered output.

    And line-height: 0 set the height of the line of text as null. Clearing the default line-height of the text.

    You can vertically align the element using vertical-align: middle rule

    button {
      height: 50px;
    }
    img {
      height: 25px;
      vertical-align: middle;
    }
    <button>
       <img src="https://www.materialui.co/materialIcons/action/search_24px.svg" alt="search" />
    </button>