Search code examples
htmlcssscale

Scale background image to element size


I am trying to have a circular image that scales to fit. I have tried the following code and the circle scales but my image doesn't scale with it. The only way the image will show inside the circle is if I put the image in as a background URL. Perhaps someone could point me in the right direction. Here is the code:

HTML

<div id="circlePicHolder" class="circularImageHolder">
      <div class="circularImage"></div>
</div>

CSS

.circularImageHolder{
     width: 100%;
     height:100%;
     padding-top:5%;
 }

 .circularImage{
        width: 100%;
        padding-bottom: 100%;
        height:0;
        background-image:url('college.gif');
        background-color:white;
        border: 1px solid red;
        margin:0 auto;
       -webkit-border-radius: 50%;
       -moz-border-radius: 50%;
       border-radius: 50%;
}

.circularImage img{
     max-width:100%;
     max-height:100%;
}

Thanks.


Solution

  • You can apply

    .circularImage{
        ...
        background-size: 100% 100%;
        ...
    }
    

    This way the background image scales as you resize

    http://jsfiddle.net/U5LLW/1/

    OR if you want to use an image, you need to make sure to apply overflow hidden or the image will not be inside of your border radius

    http://jsfiddle.net/U5LLW/3/

    .circularImage{
        overflow: hidden;
        border: 1px solid red;
        margin:0 auto;
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        border-radius: 50%;
    }
    
    .circularImage img{
        width: 100%;
    }
    

    The img should be width 100%, if you only use max-width then when the container's size exceed the image size, the image will not get any bigger. Max-width does work if you make the container smaller but not larger