gpt4 book ai didi

html - 具有纵横比的中心 Div

转载 作者:可可西里 更新时间:2023-11-01 13:29:30 25 4
gpt4 key购买 nike

我需要在 html 视口(viewport)中将一个 Div 居中。它应该在垂直和水平方向上都居中。但 Div 应保持其纵横比 (4/3) 并具有至少 10px 的边距。

我做了一个Javascript:

function resizeWindow() {
var wHeight = $(document).height() - 20;
var wWidth = $(document).width() - 20;
var gameStage = $("#gameStage");
if ((wWidth / 4) * 3 <= wHeight) {
gameStage.css("width", wWidth + "px");
gameStage.css("height", ((wWidth / 4) * 3) + "px");
gameStage.css("top", (wHeight - ((wWidth / 4) * 3)) / 2 + 9 + "px");
gameStage.css("left", "10px");
} else {
gameStage.css("height", wHeight + "px");
gameStage.css("width", ((wHeight / 3) * 4) + "px");
gameStage.css("left", (wWidth - ((wHeight / 3) * 4)) / 2 + 9 + "px");
gameStage.css("top", "10px");
}
}

https://jsfiddle.net/3sw06kvb/

但是禁用 Javascript 的用户将无法使用我的网站。使用 HTML/CSS 的解决方案应该更快(?)。

我的第一个想法是制作一个包装器

position: fixed 
top, left, bottom, right = 20px;.

但我的问题是使 div 垂直和水平居中,同时保持其纵横比。

https://jsfiddle.net/xep2mf62/

最佳答案

您可以在 CSS 中尝试以下操作。CSS3 中的新单位 vhvw 允许您根据视口(viewport)的大小设置高度。 height:100vh 将赋予元素一个等于浏览器窗口高度的高度。

***1vw = 视口(viewport)宽度的 1%

1vh = 视口(viewport)高度的 1%***

    .wrapper {
position: relative;
width:100%;
height:100vh;
}
.childdivision {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height:50vw;
width:90vw;
border:2px solid #444;
}
<div class="wrapper">
<div class="childdivision">
</div>
</div>

关于html - 具有纵横比的中心 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32218629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com