根据高度设置宽度

时间:2015-04-16 14:28:58

标签: css aspect-ratio

我看到高度的解决方案取决于宽度:css height same as width。或者在这里:https://stackoverflow.com/a/6615994/2256981。 但我的问题恰恰相反。

我的元素:

<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中做同样的事情。没有脚本。

2 个答案:

答案 0 :(得分:9)

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

高度相对于视口

您可以使用vh单位:

&#13;
&#13;
div {
  width: 75vh;
  height: 75vh;
  background:darkorange;
}
&#13;
<div></div>
&#13;
&#13;
&#13;


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

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

&#13;
&#13;
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;
}
&#13;
<div id="wrap">
    <div id="el">
        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
    </div>
</div>
&#13;
&#13;
&#13;

请注意,最后一个演示不会在窗口调整大小时更新。但纵横比保持在页面加载

更新:
正如display:inline-flex: #el {{1}}中{{1}}所述,可以解决窗口调整大小问题的更新问题。

答案 1 :(得分:-1)

编辑:错过了你想根据高度设置宽度,这恰恰相反:(


要支持所有比率,您可以使用padding-bottom。 padding-bottom中的百分比始终相对于元素的宽度:

&#13;
&#13;
/* the wrapper has a width */
.wrapper {
  position: relative;
  width: 25%;
  margin-bottom: 10px;
}
/* these elements set the height (using padding-bottom) */
.square {
  padding-bottom: 100%;
  position: relative;
}
.widescreen {
  padding-bottom: 56.25%; /* 9/16 = 0.5625 */
}

/* 
 * This is the content. 
 * Needs position:absolute to not add to the width of the parent 
 */
.content {
  /* fill parent */
  position: absolute;  
  top: 0; bottom: 0;
  left: 0; right: 0;
  
  /* visual */
  padding: 10px;
  background: orange;
  color: white;
}
&#13;
<div class="wrapper">
  <div class="square">
    <div class="content">square</div>
  </div>
</div>

<div class="wrapper">
  <div class="widescreen">
    <div class="content">16:9 ratio</div>
  </div>
</div>
&#13;
&#13;
&#13;

唯一的缺点是,你需要一堆包装元素。

相关问题