Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

Control image aspect ratios with #CSS3





Control image aspect ratios with CSS3

Control imageaspect ratios with CSS3


  • Knowledge needed: Intermediate HTML and CSS
  • Requires: Text editor, Opera 11+/WebKit nightly/other supporting browsers
  • Project time: Quicker than you might think

Making media display consistently on your site can be a problem, especially with multiple content authors. Opera’s Chris Mills shows you how object-fit and object-position can solve it

This article first appeared in issue 214 of .net magazine - the world's best-selling magazine for web designers and developers.
Controlling the aspect ratio of replaced elements, such as <img> or <video>, can be a pain. For example, you might want all images occupying the same space on a page, but to not distort and lose their aspect ratio when someone uses an image file that isn’t the right size.
Resizing and letterboxing the image slightly to conserve the aspect ratio is a much more elegant solution than squashing and stretching an image to fit. Or you might want to go the opposite way, and force letterboxed items, such as HTML5 <video>s, to conform to a specific width and height. Maybe you want all videos to be a specific aspect ratio, and want a solution where ones with different aspect ratios automatically appear correctly?
This problem is even more awkward when you’re working with a CMS that has multiple content authors uploading videos and images, especially if they’re end-users as opposed to employees. You’ll want a system that processes media so it displays consistently, but this kind of thing is quite difficult, requiring JavaScript to access and manipulate sizes on the fly, lots of CSS trickery, or lots of laborious preprocessing with a server-side language such as PHP.
CSS3 offers an easy answer that’s currently close by on the horizon. The CSS Image Values and Replaced Content module working draft defines a property called object-fit, which aims to solve exactly these sorts of problems. And this module also contains a related property, object-position, which you can use to set the horizontal and vertical position of content inside the element. All you need to fully check out the examples here is a supporting browser, such as Opera 11, or a WebKit nightly. Before going on to look at some examples, let’s explore the basic syntax of the new properties.

Object-fit

You can successfully apply object-fit to any replaced element. (A replaced element is any one whose content and appearance is defined by an external resource such as an image, video or SVG file.) The code is as follows:
  • VIEW SOURCE
  • COPY CODE
  1. img {
  2.     height: 100px;
  3.     width: 100px;
  4.     object-fit: contain;
  5. }
Note that in the code samples and examples for this article, we set the