How to center crop an image ()

后端 未结 4 1976
太阳男子
太阳男子 2020-12-22 16:40

How do I get an image to stay centered when its fluid width (percentage based) container is too small to show the whole image?

4条回答
  •  臣服心动
    2020-12-22 17:17

    When It Works

    You might have a container that holds some content such as two

    s that are 50% wide each, sitting next to each other. For this example, we can illustrate just one child of the container: enter image description here

    We'll name outer rectangle .container, the inner rectangle .content and the image img. This arrangement is perfectly fine, as long as .content is always wider than img.

    When It Breaks

    Since we're dealing with percentages and probably working with a responsive design, this may not always be the case. If .content is ever thinner than img, cropping will occur:

    enter image description here

    The Problem

    If the most interesting part of img is in the center, we need to get the browser to crop both edges evenly - leaving the best part of it visible, no matter what width of .content is.

    enter image description here

    The Solution

    Fortunately, a solution is possible. Even better, no extra markup is required.

    .content {
        width: 90%; /* or whatever is required */
        text-align: center; /* ensures the image is always in the h-middle */
        overflow: hidden; /* hide the cropped portion */
    }
    
    img {
        position: relative; /* allows repositioning */
        left: 100%; /* move the whole width of the image to the right */
        margin-left: -200%; /* magic! */
    }
    

提交回复
热议问题