html - Centering an auto-sized image both horizontally and vertically -


i've done lot of searching , found quite few answers problem, none of them seemed work when tried them in particular setup. here jsfiddle of problem trying solve:

http://jsfiddle.net/kr394ye2/1/

.classa {      background-color: yellow;      width: 50px;      height: 50px;      float: left;  }  .classb {      width: auto;      height: auto;      max-width: 50px;      max-height: 50px;  }
<div class="classa">      <img class="classb" src="https://www.google.com/logos/doodles/2015/ida-b-wells-153rd-birthday-4853060954226688-hp.jpg"></img>  </div>

i trying image, automatically sized div contained in, centered both horizontally , vertically in div. cannot make image background of div.

i have tried auto margins various types of display (inline, inline-block). i've tried text-align property, vertical-align. i've tried center tag. nothing tried has worked.

a solution should center image both horizontally , vertically.

you use inline block + pseudo element tricks.

.classa {      background-color: yellow;      width: 50px;      height: 50px;      float: left;      text-align: center;      font-size: 0;  }  .classa:after {      content: "";      height: 100%;      display: inline-block;      vertical-align: middle;  }  .classb {      width: auto;      height: auto;      max-width: 100%;      max-height: 100%;      display: inline-block;      vertical-align: middle;  }
<div class="classa">      <img class="classb" src="https://www.google.com/logos/doodles/2015/ida-b-wells-153rd-birthday-4853060954226688-hp.jpg">  </div>

note, solution works if image child inside container, plus container has known height set.

by way <img> self-closing tag, <img></img> wrong syntax, use <img src=""> or <img src="" />.


Comments