Search code examples
cssimagecenter

Center unknow image size with overflow hidden


How do I

  • vertically center an image (crop top and bottom)

  • have the image size to have width:100%

  • it's parent having overflow hidden?

    some solutions I've tried was Align image in center and middle within div and as well as others.

html

<div> 
    <a href="#"><img src=".."></a>
</div>

css

div {
  height:60px;
  width:200px;
  position: relative;
  display: block;
  overflow:hidden;
}

img {
  vertical-align:middle;
  width:100%;
}

heres a codepen for it http://codepen.io/anon/pen/oXRoxp

thanks!


Solution

  • You do have it vertically centered but the image has height 150px and your containing <div> is only 60px high. Making the <div> bigger than 150px and you will see it is aligned correctly.

    EDIT

    If you are intentionally trying to clip the image within the <div>, remove the <img> element and set it as the background using CSS.

    div {
      height:60px;
      width:200px;
      vertical-align:middle;
      display:table-cell;
      overflow:hidden;
      background: no-repeat center url('http://www.w3schools.com/css/klematis4_big.jpg') ;
    }