Recently, I've been trying to create a centered div
with an aspect ratio of 3 / 7 that fills its parent the best can, acting something like object-fit: contain
. Unfortunately, object-fit: contain
doesn't seem to work for non-replaced elements.
Here's a visualization of what I want to achieve in Flutter, which is something I have slightly more experience in.
https://dartpad.dev/?id=eec1210050a099df1c5422fa66e891e5
import 'package:flutter/material.dart';void main() { runApp(const MyApp());}class MyApp extends StatelessWidget { const MyApp({super.key}); Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: Center( child: AspectRatio( aspectRatio: 3 / 7, child: ColoredBox(color: const Color(0xFF42A5F5))), ), ), ); }}
When when the height of the container is less than its width, the box's height should be the same as its container.
Image may be NSFW.
Clik here to view.
When when the width of the container is less than its height, the box's width should be the same as its container.
Image may be NSFW.
Clik here to view.
All the while, it should always stay in the center of the screen and maintain its 7 / 3 aspect ratio.
This is what I've come up with so far, but it doesn't react to the height becoming less than the width.
* { margin: 0;}html,body { width: 100%; height: 100%;}.container { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; flex-direction: column;}.blue { background-color: royalblue; aspect-ratio: 3 / 7; flex-grow: 1; max-width: 100%;}
<div class="container"><div class="blue"></div></div>
On Discord, just_13eck suggested a solution that had this CSS instead:
body { margin: 0;}.container { display: flex; block-size: 100vh;}.blue { flex: 1 1 0; background-color: royalblue; aspect-ratio: 3 / 7; margin-inline: auto; margin-block: auto; max-inline-size: calc((3 / 7) * 100vh); max-block-size: 100%;}
And it works! BUT it only works relative to the viewport size.
Could anybody help me?I'd really appreciate it; Thanks!