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

例子

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

CSS

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

当前回答

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

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

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

其他回答

宽度:80 vmin; 身高:80 vmin;

CSS 最小视图的80%是高度还是宽度

http://caniuse.com/#feat=viewport-units

扩展顶部/底部填充技术,可以使用伪元素来设置元素的高度。使用浮动和负边距从流和视图中删除伪元素。

这允许您在不使用额外的div和/或CSS定位的情况下将内容放置在框内。

.fixed-ar::before { content: ""; float: left; width: 1px; margin-left: -1px; } .fixed-ar::after { content: ""; display: table; clear: both; } /* proportions */ .fixed-ar-1-1::before { padding-top: 100%; } .fixed-ar-4-3::before { padding-top: 75%; } .fixed-ar-16-9::before { padding-top: 56.25%; } /* demo */ .fixed-ar { margin: 1em 0; max-width: 400px; background: #EEE url(https://lorempixel.com/800/450/food/5/) center no-repeat; background-size: contain; } <div class="fixed-ar fixed-ar-1-1">1:1 Aspect Ratio</div> <div class="fixed-ar fixed-ar-4-3">4:3 Aspect Ratio</div> <div class="fixed-ar fixed-ar-16-9">16:9 Aspect Ratio</div>

这是可能的,没有任何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%;
}

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

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

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

极其简单的方法jsfiddle

HTML

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

CSS

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

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