CSS center image in a clipped parent div

2020-06-18 09:04发布

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.

标签: css
3条回答
孤傲高冷的网名
2楼-- · 2020-06-18 09:37

Hi please check example

its solve your problem

HTML

<div class='wrapper'>
    <img  border="3"/>
</div>

CSS

.wrapper {
   /*position: absolute;*/
   /* position details here */
   overflow: hidden;
   text-align:center
}
.wrapper img {
  height: 100%;
}
查看更多
疯言疯语
3楼-- · 2020-06-18 09:54

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;
    }
查看更多
Rolldiameter
4楼-- · 2020-06-18 09:56

Try to add

display:block;
margin:0px auto;

to ".wrapper img"

查看更多
登录 后发表回答