调整大小时保持div宽高比

时间:2015-02-24 09:09:21

标签: html css

我希望在浏览器调整大小时保持div的宽高比。

之前我遇到过此问题,然后解决方案使用padding-bottom百分比。

如参见。如果我想要一个类foo的div来获得宽高比2:1,我会看到一些看起来像这样的CSS。

.foo{
    width: 100%;
    padding-bottom: 50%;
}

本例(height/width)*100 = percentage中的数学(2/1)*100 = 50%。如果您想要宽高比为16:9的div,则数学为(9/16)*100 = 56.25%等。

这对我有用,但现在它没有。 我有以下fiddle所以你可以看到我的意思。

似乎.caption-wrap有一个高度,但我不知道它来自哪里。

1 个答案:

答案 0 :(得分:0)

检查这个例子:

/*
 * Pure CSS aspect ratio with no spacer images or js! :)
 */

body {
    width: 36%;
    margin: 8px auto;
}

div.stretchy-wrapper {
    width: 100%;
    padding-bottom: 56.25%; /* 16:9 */
    position: relative;

    background: blue;
}

div.stretchy-wrapper > div {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;

    color: white;
    font-size: 24px;
    text-align: center;
}

/* Other aspect ratios to try:
 * 56.25% = 16:9
 * 75% = 4:3
 * 66.66% = 3:2
 * 62.5% = 8:5
 */

链接到dabblet:http://dabblet.com/gist/2590942

相关问题