【问题标题】:set div width as a percentage of height将 div 宽度设置为高度的百分比
【发布时间】:2013-03-13 01:15:36
【问题描述】:

我正在尝试使用纯 css 设置 .full_height_div 元素的宽度,基于它的高度。它必须是相对于高度的宽度,而不是相对于宽度的高度。原因是父容器(.set_rectangle_height)已经是一个高度相对于页面宽度的 div。显然,随着页面大小的调整,页面上的divs 将调整大小,因此我无法在px 中为.full_height_div 子设置固定宽度。

所以.rectangle.set_rectangle_height 构成了父容器,其宽度占页面的百分比,高度相对于该宽度。有关此方法的说明,请参阅here

但问题是,然后我想在父级内放置一个 div,其中 height: 100% 和相对于该高度的宽度。目标是我将能够更改浏览器窗口的大小,并且所有内容都将保持其纵横比。

here is my failed attempt:

.rectangle
{
    position: relative;
    width: 30%;/*the outermost div is always a % of the page
width, even while resizing*/
    display:inline-block;
    background-color: green;
}
.set_rectangle_height
{
    padding-bottom: 30%;/*this sets the height of the outermost div
to a ratio of 1:3*/
    position: relative;
    float: left;
    width: 100%;
    height: 100%;
}
.full_height_div/*this is the div that i want to have a width relative
to its height*/
{
    height: 100%;
    width: 20px;/*i will delete this once .square_set_width is working*/
    position: absolute;
    background-color: red;
}
.square_set_width
{                   
    display: inline-block;
    padding-left: 100%; /*i want to use something like this line to set
the width of this div to be equal to .full_height_div's height - ie a 1:1 aspect
ratio, but padding-left does not work :( */
    position: relative;
    height: 100%;
    background-color: blue;
}

   <div class='rectangle'>
      <div class='set_rectangle_height'>
         <div class='full_height_div'>
            <div class='square_set_width'></div>
         </div>
      </div>
   </div>

所以,这就是上面错误标记的样子:

这就是我想要的样子:

我知道我可以在 javascript 中找到蓝色正方形百分比高度,然后将宽度设置为等于这个高度,但是如果有一个纯 css 修复来解决我正在尝试做的事情,那将非常方便。我会经常使用这种结构,我真的不想编写代码来调整页面上所有 div 的大小。

【问题讨论】:

标签: css aspect-ratio


【解决方案1】:

您必须为此使用 javascript。如果我理解你,你想要一个完美的蓝色方块。使用

var height = $('.square_set_width').height();
$('.square_set_width').css('width',height);

这是一个 jsfiddle:http://jsfiddle.net/a8kxu/

编辑:不要做padding-bottom: 30%,而是做height: 70%。这是另一个小提琴:http://jsfiddle.net/a8kxu/1/

编辑#2:抱歉,您不能使用 css 来执行此操作。不够强大

【讨论】:

  • 但是如果矩形必须随页面宽度缩放怎么办?我将更新我的示例代码,因为这可能会让人们感到困惑......
  • “矩形必须随页面宽度缩放”是什么意思?
  • 那你为什么不直接改变矩形的高度呢?
  • 我将在 5 分钟内更新问题中的代码,以便更好地说明我的意思...
【解决方案2】:

如果我理解正确的话

你可以的

#divID {
 width: 75%;
 margin-left: auto; // this is used to center the container
 margin-right: auto;// this as well
}

【讨论】:

  • 我认为你没有理解。根据我在示例中的代码,想象一个水平矩形内的正方形。
猜你喜欢
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 2012-04-05
  • 2013-08-20
  • 2012-07-13
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多