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

例子

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

CSS

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

当前回答

极其简单的方法jsfiddle

HTML

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

CSS

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

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

其他回答

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

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

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

现在最好的方法:纵横比属性(2022)

div { 纵横比:1 / 1; 宽度:50%; 边框:1px纯红色; } <div>纵横比:1 / 1</div> .


其他方法:根据视口宽度使用vw单位作为响应高度/宽度。

Vw:视口宽度的百分之一。(源MDN)

DEMO

HTML:

<div></div>

CSS为1:1的纵横比:

div{
    width:80vw;
    height:80vw; /* same as width */
}

表根据所需的纵横比和元素的宽度来计算高度。

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

这个技巧可以让你:

在元素中插入任何内容而不使用position:absolute; 没有不必要的HTML标记(只有一个元素) 根据视口的高度使用vh单位调整元素的纵横比 你可以根据视口的高度和宽度制作一个响应正方形或其他纵横比,总是适合视口(参见这个答案:响应正方形根据视口的宽度和高度或这个演示)

这些单元由IE9+支持,参见canIuse了解更多信息

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

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

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

有一种使用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%;
}