CSS square with dynamic height

我们两清 提交于 2019-12-30 11:53:32

问题


I need to make a div square. The height of the div is dynamically changing and I want the width to be equal to the height. I have seen a lot of solutions to set the height to be equal to the width (with padding-bottom on pseudo-elements), but I need it the other way arround. Is this possible with pure CSS?


回答1:


No .... well, there is this trick, where one use a hidden image

div {
  display: inline-block;
  height: 170px;
  background: red;
}
div img {
  visibility: hidden;
  height: 100%;
}
<div>
  <img src="http://placehold.it/50">
</div>

Updated

And here is a script version, that also keep it within the width

Stack snippet

(function (d,t) {
  window.addEventListener("resize", throttler, false);
  window.addEventListener("load", throttler(), false);  /*  run once on load to init  */
  
  function throttler() {
    if ( !t ) {
      t = setTimeout(function() {
        t = null;
        keepSquared(d.querySelector('.container'),
                    d.querySelector('.squared'));
       }, 66);
    }
  }
  function keepSquared(co,el) {
    var s = window.getComputedStyle(co, null);
    var m = Math.min(
      parseFloat(s.getPropertyValue("width")),
      parseFloat(s.getPropertyValue("height")));
    el.style.cssText = 
      'width: ' + m + 'px; height: ' + m + 'px;';
  }
})(document,null);
html, body {
  height: 100%;
  margin: 0;
}
.container {
  position: relative;  
  width: 50%;
  height: 50%;
  top: 50px;
  left: 50px;
  border: 1px solid black;
  box-sizing: border-box;
}
.squared {
  background-color: red;
}
<div class="container">
  <div class="squared">
  </div>
</div>

Note: Since resize events can fire at a high rate, the throttler is used to reduced the rate so the handler doesn't execute expensive operations such as DOM modifications too often.



来源:https://stackoverflow.com/questions/41362361/css-square-with-dynamic-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!