0

I have a small block and image width larger than the block. I want to block center equals image center.

Image center and block center must be on 1 vertical line. And i want to see only central part of image.

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Ruslan
  • 53
  • 7

3 Answers3

0

Instead of use negative margin on your image, you can use the transform property

.img-container{
  width:100px;
  overflow:hidden;
}
.img-container img{
  transform: translateX(-50%);
}

https://jsfiddle.net/7gk07eLm/2/

kevpoccs
  • 635
  • 5
  • 8
0

you can do this way

html

<div class="img-container">
    </div>

css:

enter code here
.img-container{
 max-width: 100px;
 min-height: 580px;
 background-repeat: no-repeat;
 background-position: center;
 background-image: url(http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg?1448476701);
}
CodeWeis
  • 846
  • 6
  • 19
0

I can think of two ways of doing this:

  1. Instead of <img> tag you can use background css property with background-position set to center, and with background-size set to cover, on <div>; in your case it's going to be something like this:

    .img-container {
    width: 100px;
    height: 500px;
    background: no-repeat center /cover url("path_to_your_image");
    }

Height property must be set!

  1. If you want to stick with <img> tag it's going to look something like this:

    .img-container {
    width: 100px;
    height: 500px;
    overflow: hidden;
    position: relative;
    }

    .img-container img {
    position: absolute;
    right: -1000%;
    left: -1000%;
    top: -1000%;
    bottom: -1000%;
    margin: auto;
    }

The crazy numbers in right, left, top and bottom positions for image are because of small size of parent <div> and big size of image itself - the percentage is based on width and height of parent block, so in this case right: 100%; will be 100px, that's why you need bigger numbers for positioning a much larger image in a smaller parent block.

Values can be tweaked, of course, as long as they are equal image will be centered.

In both cases height must be set, or it won't work!