簡體   English   中英

如何將div水平,垂直居中並保持1:1的長寬比?

[英]how to center a div horizontally, vertically, and maintain 1:1 aspect ratio?

我希望在div內有一個居中的畫布,並且無論其比例如何,都可以保持1:1的縱橫比。

通過使用以下樣式規則創建一個包含div,我可以使子元素(畫布)垂直和水平居中。

display: "flex",
alignItems: "center",
justifyContent: "center",

但是,經過大量的搜索之后,我無法找到一種增強寬高比的方法。 使用top-padding的方法有些奇怪,但在flex box的情況下似乎不起作用。

我可能會決定在其包含的div中更改畫布的相對大小,但我希望它保持居中並保持1:1的縱橫比。 哪些CSS規則可以滿足這些約束?

您將需要使用max-widthmax-height

 .container { position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; background-color:#429bf4; } .image { position: absolute; max-width: 100%; max-height: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%); } body { width: 100%; height: 100%; position: absolute; margin: 0; } 
 <div class='container'> <img class='image' src='http://via.placeholder.com/300x300'> </div> 

Flex示例

 .main { width: 200px; } .aspect1-1 { width:100%; padding-top:100%; position: relative; } .aspect1-1 div { position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color:#429bf4; display:flex; justify-content:center; align-items:center; } 
 <div class="main"> <div class="aspect1-1"> <div> <img src="http://placehold.it/100x100"> </div> </div> </div> 

如果您的主div是全屏顯示,則可以使用vmin 您需要將canvas flex-growflex-shrink0以便大小不會響應,將min-width設置為0以縮小超過canvas的隱含寬度( 300px ),使用flex-basis和高度隨height (與1:1的flex-basis相同):

flex: 0 0 100vmin;
min-width: 0;
height: 100vmin;

 body { margin: 0; } .outerdiv { display: flex; justify-content: center; align-items: center; } canvas.center { flex: 0 0 100vmin; min-width: 0; height: 100vmin; background-color: tomato; } 
 <div class="outerdiv"> <canvas class="center"></canvas> </div> 

而且,如果您需要保證金,請使用calc()作為保證金的兩倍:

flex: 0 0 calc(100vmin - 10em);
min-width: 0;
height: calc(100vmin - 10em);
margin: 5em;

 body { margin: 0; } .outerdiv { display: flex; justify-content: center; align-items: center; } canvas.center { flex: 0 0 calc(100vmin - 10em); min-width: 0; height: calc(100vmin - 10em); background-color: tomato; margin: 5em; } 
 <div class="outerdiv"> <canvas class="center"></canvas> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM