基于高度的CSS方块[重复]

时间:2022-08-27 10:15:38

This question already has an answer here:

这个问题在这里已有答案:

Is it possible to make a square div with css based on its height in pixels?

是否可以根据高度(以像素为单位)制作带css的方形div?

This question is similar to this one (marked as duplicate), but in this case I want height to be set in pixel or any unit.

这个问题类似于这个(标记为重复),但在这种情况下,我希望高度设置为像素或任何单位。

When based on width, there is a simple solution :

基于宽度,有一个简单的解决方案:

.mydiv {
    height: 0;
    padding-bottom: 100%;
}

But here 'height follows width'. I'm looking for solution where 'width follows height'. So if I would set height to 300px, width would follow it.

但这里'高度跟随宽度'。我正在寻找'宽度跟随高度'的解决方案。因此,如果我将高度设置为300px,宽度将遵循它。

For now I'm doing it using javascript, updating on window resize. But I would like to find a CSS solution, thats why I'm not looking for a javascript solution

现在我正在使用javascript,更新窗口调整大小。但我想找到一个CSS解决方案,这就是为什么我不寻找一个JavaScript解决方案

Here is a playground

这是一个游乐场

1 个解决方案

#1


2  

You could use the new viewport size units

您可以使用新的视口大小单位

JSfiddle

CSS

html,body {
    height: 100%;
    margin: 0;
}
div {
    background: red;
    height: 100vh;
    max-width:100vh;
    box-sizing: border-box;
}

Support is effectively IE9 and up

有效支持IE9及以上

#1


2  

You could use the new viewport size units

您可以使用新的视口大小单位

JSfiddle

CSS

html,body {
    height: 100%;
    margin: 0;
}
div {
    background: red;
    height: 100vh;
    max-width:100vh;
    box-sizing: border-box;
}

Support is effectively IE9 and up

有效支持IE9及以上