Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain aspect ratio according to width and height

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

like image 213
TheGr8_Nik Avatar asked May 13 '14 11:05

TheGr8_Nik


People also ask

How do you maintain aspect ratio?

In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I calculate my aspect ratio height and width?

To create an exact aspect ratio, divide the height by the width. For example: 2:3 aspect ratio: 3 ÷ 2 = 1.5, so you'd drag the slider to 150.

What does it mean to maintain aspect ratio?

If you select the Maintain Aspect Ratio check box, the embedded Mimic will retain its original proportions. This means that when you resize the embedded Mimic, its width and height will maintain their relationship, for example, if you reduce the height, the width will also reduce automatically.

How do you find the aspect ratio width?

To determine the aspect ratio of a screen: Measure the width and height of the screen. Divide the width by the height. Compare the result with the popular aspect ratios, e.g., 16:9 , to determine which standard your screen follows.


1 Answers

To maintain the aspect ratio of a div according to width and height in the viewport, you can use 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; /* <-- for IE9 */
height: 100vm; /* <-- for IE9 */
width: 100vmin; 
height: 100vmin;

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;
}
<div>whatever content you wish</div>
like image 60
web-tiki Avatar answered Oct 02 '22 18:10

web-tiki