根据高度设置宽度 [英] Set width according to height

查看:118
本文介绍了根据高度设置宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了取决于宽度的高度的解决方案: css高度与宽度相同.或者在这里: https://stackoverflow.com/a/6615994/2256981 . 但是我的问题是相反的.

I saw solution for height depending on width: css height same as width. Or here: https://stackoverflow.com/a/6615994/2256981. But my question is opposite.

我的元素:

<body>
    <div id="square"></div>
</body>

样式:

body, html {
    margin: 0;
    height: 100%;
    min-height: 300px;
    position: relative;
}
div#square { /* My square. */
    height: 75%; /* It's height depends on ancestor's height. */
    width: 75vh; /* If supported, preliminarily sets it's width. */
    position: absolute; /* Centers it. */
    left: 50%; top: 50%; transform: translate(-50%, -50%);
    background-color: darkorange; /* Makes it visible. */
}

脚本,使它保持方形:

window.onload = window.onresize = function (event) {
    var mySquare = document.getElementById("square");
    mySquare.style.width = mySquare.offsetHeight + 'px';
};

在此处完成代码: http://jsfiddle.net/je1h/hxkgfr9g/

问题是要在纯CSS中做同样的事情.没有脚本.

The question is to make the same thing in pure CSS. No scripting.

推荐答案

我知道有两种技术可以根据元素的高度保持元素的长宽比:

There are two techiques I am aware of to keep the aspect ratio of an element according to it's height :

高度相对于视口时:

您可以使用vh单位:

div {
  width: 75vh;
  height: 75vh;
  background:darkorange;
}

<div></div>

对于基于父元素高度的高度:

For a height based on the height of a parent element :

您可以使用具有所需纵横比的虚拟图像.宽高比为1:1的示例可以使用1 * 1透明.png图像,或者@vlgalik注释为1 * 1 base64编码的gif:

You can use a dummy image that has the aspect ratio you want. Example with a 1:1 aspect ratio you can use a 1*1 transparent .png image or as commented by @vlgalik a 1*1 base64 encoded gif :

html,body{
    height:100%;
    margin:0;
    padding:0;
}
#wrap{
    height:75%;
}
#el{
    display:inline-block;
    height:100%;
    background:darkorange;
}
#el img{
    display:block;
    height:100%;
    width:auto;
}

<div id="wrap">
    <div id="el">
        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
    </div>
</div>

请注意,此最后一个演示不会在调整窗口大小时更新.但是长宽比会保持在页面加载量上

更新:
将注释设置为display:inline-flex: #el似乎解决了窗口大小调整的更新问题.

UPDATE :
As reported in the comments setting display:inline-flex: on #el seems to solve the updating on window resize problem.

这篇关于根据高度设置宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆