CSS square with dynamic height

前端 未结 1 623
天命终不由人
天命终不由人 2021-01-16 10:00

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 sol

相关标签:
1条回答
  • 2021-01-16 10:40

    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.

    0 讨论(0)
提交回复
热议问题