根据高度保持div宽高比

根据高度保持div宽高比

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

问题描述

我需要将元素的宽度维持为高度的百分比。



相反的是通过使用padding-top的%值可以实现,但是padding-left作为百分比将是一个



因此,使用标记:

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

我想使用这样的:

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

为了确保箱子的 / strong>。高度是流动的,因为它的%margin - 随着窗口的高度变化,框的高度也会。



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

解决方案

您可以使用具有所需比例的图像来帮助比例尺寸可以通过将一个维度设置为某个值,而将其他设置为auto)来按比例缩放。图片不一定要显示,但必须占用空间。



  .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-helpersrc =// dummyimage.com/200x100/999/000width =200height =100> < div class =inner>箱具有流体高度< br> img具有2:1的纵横比,100%的高度,自动宽度,静态位置< br>因此它保持宽度=高度的200% 2.2它定义了盒子的尺寸< br> 3.内部扩展与框< / div>< / div>  

$ b

在上面的例子中,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宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:06