CSS scale height to match width - possibly with a formfactor

前端 未结 10 1735
天涯浪人
天涯浪人 2020-12-04 11:28

I have implemented a GoogleMapsV3 map in a twitterBootstrap basic responsive design site.

But my question is quite simple: i have:

相关标签:
10条回答
  • 2020-12-04 11:40
    .video {
        width: 100%;
        position: relative;
        padding-bottom: 56.25%; /* ratio 16/9 */
    }
    
    .video iframe {
        border: none;
        position: absolute;
        width: 100%;
        height: 100%;
    }
    

    16:9

    padding-bottom = 9/16 * 100 = 56.25

    0 讨论(0)
  • 2020-12-04 11:49

    You can set its before and after to force a constant width-to-height ratio

    HTML:

    <div class="squared"></div>
    

    CSS:

    .squared {
      background: #333;
      width: 300px; 
    }
    .squared::before {
      content: '';
      padding-top: 100%;
      float: left;
    }
    .squared::after {
      content: '';
      display: block;
      clear: both;
    }
    
    0 讨论(0)
  • 2020-12-04 11:49

    Solution with Jquery

    $(window).resize(function () {
        var width = $("#map").width();
        $("#map").height(width * 1.72);
    });
    
    0 讨论(0)
  • 2020-12-04 11:55

    Let me describe the JS solution as a separate answer:

    function handleResize()
    {
      var mapElement = document.getElementById("map");
      mapElement.style.height = (mapElement.offsetWidth * 1.72) + "px";
    }
    
    <div id="map" onresize="handleResize()">...</div>
    

    (or register the event listener dynamically).

    mapElement.style.width * 1.72 will not work, since it requires that the width be set explicitly on the element, either using the width DOM attribute or in the inline style's width CSS property.

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