Having a div
element that adjusts its height based on width to maintain aspect ratio, I aim to place this div
within another while maximizing available space vertically and horizontally without any cropping. It seems that object-fit: contain
, typically used for images, may be the closest option.
The goal is to ensure the div covers the maximum height and width possible while still adhering to the aspect ratio, with no crop in either vertical or horizontal directions.
Can this be achieved using CSS alone? If so, how?
Want more insight? Check out this informative article.
Code snippet (or any alternate solution):
html,
body {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 100%;
}
.container:before {
content: "";
display: block;
width: 50%;
padding-top: 50%;
}
.embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: red;
}
<div class="container">
<div class="embed">
this should accommodate all the available space and maintain aspect ratio, no crop when width is too wide
</div>
</div>