How to Make Div Element Auto-Resize Maintaining Aspect Ratio

How to make div element auto-resize maintaining aspect ratio?

The aspect-ratio ref property has a good support now so you can use the below:

body {
height: 100vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: gray;
}


.stage {
--r: 960 / 540;

aspect-ratio: var(--r);
width:min(90%, min(960px, 90vh*(var(--r))));

display: flex;
justify-content: center;
align-items: center;


background:
/* this gradient is a proof that the ratio is maintained since the angle is fixed */
linear-gradient(30deg,red 50%,transparent 50%),
chocolate;
}
<div class="stage">
<p>Some text</p>
</div>

How to Auto-Resize a DIV with CSS while keeping Aspect Ratio?

Since percentage values of the padding-* properties are calculated with respect to the width of the generated box's containing block, you could:

  • Add a dummy element with no content but with a percentage in a vertical padding (padding-top or padding-bottom), corresponding to the desired aspect ratio.
  • Use absolutely positioning to remove all contents from the normal flow of the element, in order to prevent them from increasing the height. Then, make it grow to fill the container.

This idea is taken from http://ansciath.tumblr.com/post/7347495869/css-aspect-ratio

#container {  position: relative;  width: 50%;}#dummy {  padding-top: 75%; /* 4:3 aspect ratio */}#element {  position: absolute;  top: 0;  bottom: 0;  left: 0;  right: 0;  background-color: silver;}
<div id="container">  <div id="dummy"></div>  <div id="element">    some text  </div></div>

CSS resize div whilst maintaining aspect ratio of containing image

Try to apply this style and remove inline-styling from element:

#triangle {
height:500px;
width: max-content;
}

img {
height:100%;
}

Maintain the aspect ratio of a div with CSS

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

.demoWrapper {
padding: 10px;
background: white;
box-sizing: border-box;
resize: horizontal;
border: 1px dashed;
overflow: auto;
max-width: 100%;
height: calc(100vh - 16px);
}

div {
width: 100%;
padding-bottom: 75%;
background: gold; /** <-- For the demo **/
}
<div class="demoWrapper">
<div></div>
</div>

How do I auto-resize an image to fit a 'div' container?

Do not apply an explicit width or height to the image tag. Instead, give it:

max-width:100%;
max-height:100%;

Also, height: auto; if you want to specify a width only.

Example: http://jsfiddle.net/xwrvxser/1/



Leave a reply



Submit