CSS Circular Cropping of Rectangle Image

前端 未结 9 1355
北荒
北荒 2020-12-12 15:32

I want to make a centered circular image from rectangle photo. The photo\'s dimensions is unknown. Usually it\'s a rectangle form. I\'ve tried a lot of methods:

CSS:

相关标签:
9条回答
  • 2020-12-12 16:13

    The best way I've been able to do this is with using the new css object-fit (1) property and the padding-bottom (2) hack.

    You need a wrapper element around the image. You can use whatever you want, but I like using the new HTML picture tag.

    .rounded {
      display: block;
      width: 100%;
      height: 0;
      padding-bottom: 100%;
      border-radius: 50%;
      overflow: hidden;
    }
    
    .rounded img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    
    /* These classes just used for demo */
    .w25 {
      width: 25%;
    }
    
    .w50 {
      width: 50%;
    }
    <div class="w25">
    <picture class="rounded">
      <img src="https://i.imgur.com/A8eQsll.jpg">
    </picture>
    </div>
    
    <!-- example using a div -->
    <div class="w50">
    <div class="rounded">
      <img src="https://i.imgur.com/A8eQsll.jpg">
    </div>
    </div>
    
    <picture class="rounded">
      <img src="https://i.imgur.com/A8eQsll.jpg">
    </picture>

    References

    1. CSS Image size, how to fill, not stretch?

    2. Maintain the aspect ratio of a div with CSS

    0 讨论(0)
  • 2020-12-12 16:14

    If you can live without the <img> tag, I suggest you use the photo as a background image.

    .cropcircle{
        width: 250px;
        height: 250px;
        border-radius: 100%;
        background: #eee no-repeat center;
        background-size: cover;
    }
    
    #image1{
        background-image: url(http://www.voont.com/files/images/edit/7-ridiculous-ways-boost-self-esteem/happy.jpg);
    }
    <div id="image1" class="cropcircle"></div>

    0 讨论(0)
  • 2020-12-12 16:14

    I know many of the solutions mentioned above works, you can as well try flex.

    But my image was rectangular and not fitting properly. so this is what i did.

    .parentDivClass {
        position: relative;
        height: 100px;
        width: 100px;
        overflow: hidden;
        border-radius: 50%;
        margin: 20px;
        display: flex;
        justify-content: center;
    }
    

    and for the image inside, you can use,

    child Img {
        display: block;
        margin: 0 auto;
        height: 100%;
        width: auto;
    }
    

    This is helpful when you are using bootstrap 4 classes.

    0 讨论(0)
提交回复
热议问题