css3 image sizing and aspect ratio

Recently I came across some interesting features of css3 and its uses for sizing images. There are a number of new properties that allow us to have greater control over how our images are displayed We are all familiar with the task of updating an image on a webpage. We can either upload the new image which has a different filename and then edit the html or css that defines the image or we can simply upload a new image with the same filename. With either of these attempts you will have to be aware of the sizing of the image and that if you just replace the image and its a different size you will need to make sure it isn’t being constrained by the previous images size and giving you a “squashed” image. Well with the use of object-fit we can easily set any image to fit the dimensions we set and still keep its aspect ratio. There are 3 values for the object-fit and they are contain, fill and cover. Contain To use contain you need to set the width and height of the object and the content will be resized to fully display within this size. Fill The fill value causes the object to expand to completely fill the dimensions set for it even if this doesn’t keep the aspect ratio. Cover Lastly the cover value keeps the aspect ratio of the image but attempts to alter the width and height to expand to the content size. With this object-fit property is also the object-position which just like background-position allows us to position the content within the element using the same kind of values. Heres some example css of an image set to 500 pixels width and height but with an image used that doesn’t match the dimensions. See how using the object-contain it changes the display.

<style type="text/css">
    	img {
    		border:1px solid red;
<img src="garden.jpg" alt="garden" />

Note that the actual size of the image is 400px wide by 300px in height. object contain With this of course being css3 there is some support for various browsers but not all of them. Infact i only got this working with Opera, however the latest browsers should support the use of these properties soon so keep an eye open for this one.


  • avatar-jesper-cms-spang
    # Jesper CMS Spang

    This is quite exciting, and hopefully this will make it into webkit real soon as it correspends great with how views work on the Android platform.

    Thanks for sharing!

  • avatar-davidejones
    # davidejones

    Thanks, glad you enjoyed it :)

    Yea i was pretty interested in this when i discovered this, i imagine it won’t be too much longer before webkit catches up.

  • avatar-jeremy-law
    # Jeremy Law
    Very cool! Just what I was looking for!
  • avatar-g-bess
    # G Bess
    It works like a charm

Comments are currently closed