”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在可重中的DIV元素中保持长宽比?

如何在可重中的DIV元素中保持长宽比?

发布于2025-03-04
浏览:816

在创建保持在屏幕上的可供位数的div元素时,在自动衡量的div元素How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?

在调整大小div元素时提供了一个简单的解决方案。以下CSS代码演示了如何实现这一目标:

body { 身高:100VH; 保证金:0; 显示:Flex; Jusify-content:中心; 准项目:中心; 背景:灰色; } 。阶段 { -r:960 /540; //定义所需的纵横比(宽度 /高度) 方面比例:var(-r); //设置纵横比 宽度:最小(90%,最小(960px,90vh*(var(-r)))); //设置最大宽度和高度,同时保持比率 显示:Flex; Jusify-content:中心; 准项目:中心; 背景: 线性毕业生(30维,红色50%,透明50%),//添加梯度以可视化保留的长宽比 巧克力; }

Explanation:

The aspect-ratio property establishes the desired aspect ratio for the element, which is calculated based on the initial width and height values (960px and 540px, respectively).

The width property ensures that the element's width remains within指定的约束:

可用宽度的90%的最大90%
body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
}

.stage {
  --r: 960 / 540;  // Define the desired aspect ratio (width / height)

  aspect-ratio: var(--r);  // Set the aspect ratio
  width:min(90%, min(960px, 90vh*(var(--r))));  // Set the maximum width and height while preserving ratio

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

  background: 
    linear-gradient(30deg,red 50%,transparent 50%),  // Add a gradient to visualize the preserved aspect ratio
    chocolate;
}
与可用高度有关添加到视觉上证明了纵横比的维持,因为梯度的角度保持不变,而不管元素维度的变化如何。

在屏幕上保持窗口空间,并在窗口方面保持较高的方面,并依靠窗口,并将其定为符合窗口,并在屏幕上维护的是,并依赖于所需的方面。该解决方案有效地调整了元素的宽度和高度。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3