【发布时间】:2015-11-20 00:30:16
【问题描述】:
我需要在 html 视口中将一个 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 在保持纵横比的同时垂直和水平居中。
【问题讨论】:
-
你的意思是这样的吗? jsfiddle.net/kpLzp9kj/1(这不是完美的结果,但是..)
标签: html css centering aspect-ratio