Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Maintain aspect ratio according to width and height

Maintain aspect ratio according to width and height

Problem

It is possible to fit and center a square div in the viewport and always maintain it's aspect ratio according to width and height?

Requirements :

  • only CSS
  • the size of the square must adapt to the smallest dimension (width or height) of viewport regardless of the orientation (landscape or portrait) of the viewport.
  • the square must be centered horizontaly and verticaly in the viewport

Example:

Maintain aspect ratio according to width and height of viewport

Problem courtesy of: TheGr8_Nik

Solution

To maintain the aspect ratio of a div according to width and height in the viewport, you can uses one HTML tag with:

  1. vmin units for the sizing :

    vmin 1/100th of the minimum value between the Height and the Width of the viewport.
    (source : MDN)

  2. position: absolute and margin: auto; for the centering

DEMO (resize both window height and width to see it in action)

Features :

  • keeps it's aspect ratio according to width and height
  • stays centered in viewport horizontaly and verticaly
  • never overflows the viewport

Browser support :

vmin units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback with vm units instead of vmin like this :

width: 100vm; /* 

Full code:

body {
  margin:0; /* To prevent scrollbars */
}

div{
  /* Aspect ratio */
  height:100vm; width:100vm; /* IE9 fallback */
  width: 100vmin; 
  height: 100vmin;
  /*Centering */
  position: absolute;
  top:0;bottom:0;
  left:0;right:0;
  margin: auto;
  /* styling */
  background: gold;
}
whatever content you wish
Solution courtesy of: web-tiki

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Maintain aspect ratio according to width and height

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×