」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在可重中的DIV元素中保持長寬比?

如何在可重中的DIV元素中保持長寬比?

發佈於2025-03-04
瀏覽:320

在創建保持在屏幕上的可供位數的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