CSS - aspect-ratio



The aspect-ratio property of CSS is useful in defining the desired width-to-height ratio of an element's box. This property is helpful when the size of parent container or viewport changes, the browser will re-adjust the dimensions of the element, in order to maintain the width-to-height ratio.

It is useful in calculation of auto sizes and other layout functions.

Minimum one size of the box should be automatic, in order to see the effect of aspect-ratio. Provided aspect-ratio has no effect when neither the width, nor the height is an automatic size.

Possible Values

The aspect-ratio property can have one of the following values:

  • auto: Replaced elements such as <img> uses the intrinsic aspect-ratio.

  • <ratio>: Box's preferred aspect-ratio is the ratio of width / height. When height and the preceding slash symbol is not specified, it defaults to 1. It works based on the dimensions of the box that is specified by box-sizing.

Applies To

All html elements except inline boxes and internal ruby or table boxes.

Syntax

aspect-ratio = auto || <ratio>  

<ratio> are numbers relating to the ratio of width / height, such as 9/4.

CSS aspect-ratio - Fallback to natural aspect-ratio

Following example demonstrates that an image is loaded with its natural aspect ratio and how to declare a fallback option.

<html>
<head>
<style>
   img {
      display: block;
      width: 200px;
      border: 3px dotted blue;
      background-color: lightgreen;
      margin-bottom: 5px;

      aspect-ratio: 5/2 auto;
   }
</style>
</head>
<body>
   <p>with "5/2" aspect-ratio</p>
   <img src="" /> 
   <p>with "auto" aspect-ratio</p>
   <img src="images/red-flower.jpg" />
</body>
</html>

In the above example, the first <img> has no src specified, and that is displayed with aspect-ratio = 5/2; whereas the second <img> has src specified and it is displayed with its natural aspect-ratio. auto is the fallback option given.

CSS aspect-ratio - Using aspect-ratio with fixed width

Following example demonstrates the different aspect-ratio values with fixed width and height as auto.

<html>
<head>
<style>
   #container {
      display: inline-block;
      width: 100px;
      height: auto;
      border: 2px solid blue;
      background-color: yellow;
      margin-right: 10px;
   }
   .sample1{
      aspect-ratio: 5/2;
   }

   .sample2{
      aspect-ratio: 0.5;
   }

   .sample3{
      aspect-ratio: 2;
   }

   .sample4 {
      aspect-ratio: 18/9;
   }
</style>
</head>
<body>
   <div id="container" class="sample1">aspect-ratio: 5/2</div>
   <div id="container" class="sample2">aspect-ratio: 0.5</div>
   <div id="container" class="sample3">aspect-ratio: 2</div>
   <div id="container" class="sample4">aspect-ratio: 18/9</div>
</body>
</html>
Advertisements