是否可以设置相同的高度和宽度(比例1:1)?

例子

+----------+
| body     |
| 1:3      |
|          |
| +------+ |
| | div  | |
| | 1:1  | |
| +------+ |
|          |
|          |
|          |
|          |
|          |
+----------+

CSS

div {
  width: 80%;
  height: same-as-width
}

当前回答

有一种使用CSS的方法!

如果你根据父容器设置宽度,你可以将height设置为0,并将padding-bottom设置为百分比,该百分比将根据当前宽度计算:

.some_element {
    position: relative;
    width: 20%;
    height: 0;
    padding-bottom: 20%;
}

这在所有主流浏览器中都运行良好。

JSFiddle: https://jsfiddle.net/ayb9nzj3/

其他回答

真的,这是对内森的回答的一个评论,但我还不允许这样做…… 我想保持纵横比,即使盒子里有太多东西装不下。他的例子扩大了高度,改变了纵横比。我发现

overflow: hidden;
overflow-x: auto;
overflow-y: auto;

对元素有帮助。参见http://jsfiddle.net/B8FU8/3111/

使用jQuery,您可以通过以下操作来实现这一点

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

在http://jsfiddle.net/n6DAu/1/上查看工作示例

有一种使用CSS的方法!

如果你根据父容器设置宽度,你可以将height设置为0,并将padding-bottom设置为百分比,该百分比将根据当前宽度计算:

.some_element {
    position: relative;
    width: 20%;
    height: 0;
    padding-bottom: 20%;
}

这在所有主流浏览器中都运行良好。

JSFiddle: https://jsfiddle.net/ayb9nzj3/

这是可能的,没有任何Javascript:)

HTML:

<div class='box'>
    <div class='content'>Aspect ratio of 1:1</div>
</div> 

CSS:

.box {
    position: relative;
    width:    50%; /* desired width */
}

.box:before {
    content:     "";
    display:     block;
    padding-top: 100%; /* initial ratio of 1:1*/
}

.content {
    position: absolute;
    top:      0;
    left:     0;
    bottom:   0;
    right:    0;
}

/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
    padding-top: 50%;
}
.ratio1_2:before{
    padding-top: 200%;
}
.ratio4_3:before{
    padding-top: 75%;
}
.ratio16_9:before{
    padding-top: 56.25%;
}

极其简单的方法jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}