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

例子

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

CSS

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

当前回答

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

这允许您在不使用额外的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>

其他回答

有一种使用CSS的方法!

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

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

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

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

[更新:虽然我是独立发现这个技巧的,但我后来知道Thierry Koblentz打败了我。你可以在A List Apart上找到他2009年的文章。该表扬就表扬。]

我知道这是一个老问题,但我遇到过一个类似的问题,我只用CSS解决了。这是我的博客文章讨论的解决方案。文章中有一个活生生的例子。代码转载如下。

#{容器 显示:inline-block; 位置:相对; 宽度:50%; } #假{ margin-top: 75%; /* 4:3纵横比*/ } #{元素 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 背景色:银色/*给我看看!* / } < div id = "容器" > < div id = "假" > < / div > < div id = "元素" > 一些文本 < / div > < / div >

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

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

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

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

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

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

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