How to center and crop an image to always appear in square shape with CSS?

后端 未结 9 1291
[愿得一人]
[愿得一人] 2020-12-02 06:19

I need to always crop a random-sized image to a square 160x160 using only CSS. The images should stay centered when cropped.

My markup should be:

<         


        
相关标签:
9条回答
  • 2020-12-02 07:15

    object-fit property does the magic. On JsFiddle.

    CSS

    .image {
      width: 160px;
      height: 160px;
    }
    
    .object-fit_fill {
      object-fit: fill
    }
    
    .object-fit_contain {
      object-fit: contain
    }
    
    .object-fit_cover {
      object-fit: cover
    }
    
    .object-fit_none {
      object-fit: none
    }
    
    .object-fit_scale-down {
      object-fit: scale-down
    }
    

    HTML

    <div class="original-image">
      <p>original image</p>
      <img src="http://lorempixel.com/500/200">
    </div>
    
    <div class="image">
      <p>object-fit: fill</p>
      <img class="object-fit_fill" src="http://lorempixel.com/500/200">
    </div>
    
    <div class="image">
      <p>object-fit: contain</p>
      <img class="object-fit_contain" src="http://lorempixel.com/500/200">
    </div>
    
    <div class="image">
      <p>object-fit: cover</p>
      <img class="object-fit_cover" src="http://lorempixel.com/500/200">
    </div>
    
    <div class="image">
      <p>object-fit: none</p>
      <img class="object-fit_none" src="http://lorempixel.com/500/200">
    </div>
    
    <div class="image">
      <p>object-fit: scale-down</p>
      <img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
    </div>
    

    Result

    0 讨论(0)
  • 2020-12-02 07:15

    clip property with position may help you

    a{
    position:absolute;
    clip:rect(0px,200px,200px,0px);
    }
    
    a img{
    position:relative;
    left:-50%;
    top:-50%;
     }
    

    WORKING FIDDLE

    0 讨论(0)
  • 2020-12-02 07:19

    HTML:

    <div class="thumbnail">
    </div>
    

    CSS:

    .thumbnail { 
    background: url(image.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
    width: 250px;
    height: 250px;
    }
    
    0 讨论(0)
提交回复
热议问题