【问题标题】:Center Div with aspect Ratio具有纵横比的中心 Div
【发布时间】: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 在保持纵横比的同时垂直和水平居中。

https://jsfiddle.net/xep2mf62/

【问题讨论】:

标签: html css centering aspect-ratio


【解决方案1】:

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

***1vw = 视口宽度的 1%

1vh = 视口高度的 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>

【讨论】:

  • 问题不只是让div居中,而是保持他的比例(动态宽度和高度)
  • 在这种情况下,可以使用viewport作为单位设置高度。
  • 那是我在问题评论中向@LittleSatan 提出的建议 =)
  • 如果浏览器的宽度远大于高度,则 div 的高度会变大。它不再适合视口。在我的 javascript 中,div 将始终完全可见。
【解决方案2】:

仍然是 JS,但更简单

window.onresize = function() {
  resize();
};

function resize() {
  var wrapper = document.querySelector(".wrapper");
  var wrapperwidth = 1920;
  var wrapperheight = 1080;
  var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  var ratio = Math.min(vw / wrapperwidth, vh / wrapperheight);
  wrapper.style.transform = `translate(-50%, -50%) scale(${ratio})`;
}

resize();
.wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 1919px;
  height: 1079px;
  overflow: hidden;
  background-color: red;
}

/* demo text (smiley face) */

.wrapper::after {
  content: ":)";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 200px;
  font-family: "Roboto", 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
&lt;div class="wrapper"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2018-08-21
    • 1970-01-01
    • 2021-11-14
    • 2013-09-19
    • 2018-05-24
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多