Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS center image in a clipped parent div

Tags:

css

How can I center an img in a parent div tag which is set to overflow: hidden. That is, what I want is to clip the image but clip on both the left/right so the middle of the image is shown.

<div class='wrapper'>
  <img/>
</div>

Then styles something like:

.wrapper {
  position: absolute;
  /* position details here */
  overflow: hidden;
}
.wrapper img {
  height: 100%;
  margin-left: -??; //what here?
}

-50% would be the width of the parent, but I want the width of the img itself.

Firefox supported CSS is acceptable.

like image 873
edA-qa mort-ora-y Avatar asked Jun 27 '13 07:06

edA-qa mort-ora-y


2 Answers

http://codepen.io/gcyrillus/pen/BdtEj

use text-align , line-height , vertical-align and negative margin. img virtually reduced to zero, will center itself.

.wrapper {
  width:300px;
  text-align:center;
  line-height:300px;
  height:300px;
  border:solid;
  margin:2em auto;
  overflow:visible; /* let's see what we slice off */
}
img {margin:-100%;vertical-align:middle;

  /* to show whats been cut off */
  position:relative;
  z-index:-1;
}

For horizontal only :

  .wrapper {
      width:300px;
      text-align:center;
      border:solid;
      margin:2em auto;
      overflow:hidden
    }
    img {
      margin:0 -100%;
      vertical-align:middle;
    }
like image 89
G-Cyrillus Avatar answered Sep 25 '22 10:09

G-Cyrillus


Try to add

display:block;
margin:0px auto;

to ".wrapper img"

like image 20
Hexo Avatar answered Sep 22 '22 10:09

Hexo