Issue
Given a parent HTML div element that can resize both vertical and horizontal, I want the child div to maintain aspect ratio (for example, 16:9), be centered in and restrained by the edges of the parent. No JS please.
Is this possible with CSS alone? (The top "wider" parent image example is pillarbox, and the bottom "narrower" is letterbox.)
Note: the parent will be smaller than the actual browser viewport in most cases, so don't judge your answer (for example) bases on the width or height of the browser viewport. This should be able to stand alone at any given parent / child size.
Solution
Solution
Nearly four years later, @container
queries and aspect-ratio
provide a very nice solution!
<div class="resize-at-will">
<div class="maintain-aspect-ratio">
...
</div>
</div>
<style>
.resize-at-will {
container-type: size;
display: flex;
justify-content: center;
align-items: center;
}
.maintain-aspect-ratio {
aspect-ratio: 16 / 9;
width: 100%;
background-color: #ff3e00;
}
@container (min-aspect-ratio: 16 / 9) {
.maintain-aspect-ratio {
width: auto;
height: 100%;
}
}
</style>
- See this CodePen for an implementation: https://codepen.io/arxpoetica/pen/JjZdwpB
- Also see the Svelte REPL version if that's your flavor: https://svelte.dev/repl/0896d71005944bb6a7cf5463592b533b?version=3.52.0
Caveats
Note, it's not responsive to the viewport, but actually responsive to the parent div with the container-type: size;
CSS declaration. If you want responsive to viewport, just use @media ([min/max]-aspect-ratio: x / x) { ... }
Also note, container queries are in most modern browsers, but not yet Firefox. However, there's a polyfill: https://developer.chrome.com/blog/cq-polyfill/#the-container-query-polyfill
Further Information
- https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries
- https://caniuse.com/mdn-css_at-rules_container
Answered By - arxpoetica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.