根据高度保持 div 纵横比 [英] Maintain div aspect ratio according to height

查看:36
本文介绍了根据高度保持 div 纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将元素的宽度保持为其高度的百分比.所以随着高度的变化,宽度也会更新.

相反,可以通过为 padding-top 使用 % 值来实现,但 padding-left 作为百分比将是对象宽度的百分比,而不是其高度.

使用这样的标记:

<div class="inner"></div>

我想使用这样的东西:

.box {位置:绝对;保证金最高:50%;底部:0;}.内{填充左:200%;}

确保框的纵横比根据其高度保持不变.高度是可变的,因为它是边距百分比 - 随着窗口高度的变化,框的高度也会发生变化.

我知道如何用 JavaScript 实现这一点,只是想知道是否有一个干净的纯 CSS 解决方案?

解决方案

您可以使用具有所需比例的图像来帮助按比例调整大小(可以通过将一个维度设置为某个值并将其他维度设置为自动来按比例缩放图像).图像不一定要可见,但必须占据空间.

.box {位置:绝对;底部:0;左:0;高度:50%;}.size-helper {显示:块;宽度:自动;高度:100%;}.内{位置:绝对;顶部:0;底部:0;左:0;右:0;背景:rgba(255, 255, 153, .8);}

<img class="size-helper" src="//dummyimage.com/200x100/999/000" width="200" height="100"><div class="inner">1.盒子有流体高度
2. img 具有 2:1 的纵横比、100% 的高度、自动宽度、静态位置
2.1 因此它保持宽度 = 高度的 200%2.2 它定义了盒子的尺寸<br>3. 内部膨胀和盒子一样多

在上面的例子中,box、inner 和 helper 的大小都是一样的.

I need to maintain the width of an element as a percentage of its height. So as the height changes, the width is updated.

The opposite is achievable by using a % value for padding-top, but padding-left as a percentage will be a percentage of the width of an object, not its height.

So with markup like this:

<div class="box">
  <div class="inner"></div>
</div>

I'd like to use something like this:

.box {
    position: absolute;
    margin-top: 50%;
    bottom: 0;
}
.inner {
    padding-left: 200%;
}

To ensure the box's aspect ratio is maintained according to it's height. The height is fluid because of it's % margin - as the window's height changes, the box's height will too.

I know how to achieve this with JavaScript, just wondering if there's a clean CSS-only solution?

解决方案

You can use an image that has the desired proportions as to help with proportional sizing (images can be scaled proportionally by setting one dimension to some value and other to auto). The image does not have to be visible, but it must occupy space.

.box {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 50%;
}
.size-helper {
  display: block;
  width: auto;
  height: 100%;
}
.inner {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 153, .8);
}

<div class="box">
  <img class="size-helper" src="//dummyimage.com/200x100/999/000" width="200" height="100">
  <div class="inner">
    1. box has fluid height<br>
    2. img has 2:1 aspect ratio, 100% height, auto width, static position<br>
    2.1 it thus maintains width = 200% of height<br>
    2.2 it defines the dimensions of the box<br>
    3. inner expands as much as box
  </div>
</div>

In the above example, box, inner and helper are all same size.

这篇关于根据高度保持 div 纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆