javascript - 当高度是限制因素时保持 div 比率

标签 javascript html css

我正在尝试创建一个“幻灯片”div,它以恒定的纵横比在屏幕中间居中。

结合这个trick用于居中和this one对于比率,我想出了这个:

HTML

<div class="slide">
    <div class="slide-content">
        Percentage sized and still centered.
    </div>
</div>

CSS

/* slide centered in the middle of the screen + width = 80% */
.slide {
    position: fixed;
    width: 80%;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: red;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
}   

/* aspect ratio of 2:1 */
.slide:before{
    content: "";
    display: block;
    padding-top: 50%;
}

/* stretch the content to the slide size */
.slide > .slide-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 40px 60px;
    transition: all 0.6s ease-in-out;
}

fiddle 在这里:https://jsfiddle.net/3jph853w/

它工作得很漂亮,希望在横向 View 中的移动设备上:基于宽度的技巧,div 没有正确调整大小并且它的一部分“溢出”在屏幕之外。当您垂直调整 fiddle 输出的大小时,您可以看到它。

我该如何解决?我宁愿只保留它的 css,需要额外的 html 标记。我对 JS 持开放态度,但我的元素是基于 Angular 的,不使用 jQuery。

最佳答案

这可能是一个开始

Fiddle demo 100% 视口(viewport)
Fiddle demo视口(viewport)的 80%

html, body{
  margin: 0;
}
.slide{
  position: absolute;
  width: calc(100vh * 2);
  height: calc(100vw * 0.5);
  max-width: 100vw;
  max-height: 100vh;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.slide-content{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: red;
  padding: 40px 60px;
  box-sizing: border-box;
  transition: all 0.6s ease-in-out;
}
<div class="slide">
  <div class="slide-content">
    Percentage sized and still centered.
  </div>
</div>

关于javascript - 当高度是限制因素时保持 div 比率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38110558/

相关文章:

javascript - 用 HTML 制作一个简单的终端

html - 是否可以在父元素中使用 zen 编码索引来应用于子元素?

php - WordPress 网站页脚中的链接不可点击

javascript - jsf 命令按钮中的 onclick 在 chrome 中不起作用

javascript - 隐藏/保护 Windows 8 应用程序中的 Javascript 源代码

javascript - d3 将新的键值添加到现有的 json 数据中

html - 将图像垂直居中到多列容器 Bootstrap 4 中的文本?

使用 HTML 变量进行 PHP 分页

java - 如何从Java中的JavascriptExecutor返回字符串

html - 标题和描述标签中的重音