Square DIV where height is equal to viewport

前端 未结 8 1300
我在风中等你
我在风中等你 2020-12-01 06:13

I need to create a DIV where width=height, and height=100% of the viewport (which, obviously, is variable).

In other words, a perfectly sq

相关标签:
8条回答
  • 2020-12-01 06:31

    This is interesting...

    For those who may be looking for a pure CSS way to contain a square div with the maximum dimensions:

    The key takeaway here is that you set max-width and max-height while setting width and height to the opposite values.

    HTML

    <div>
    </div>
    

    CSS

    html, body {
      margin: 0;
      padding: 0;
      width: 100vw;
      height: 100vh;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
    
    div {
      background-color: red;
      width: 100vh;
      height: 100vw;
      max-width: 100vw;
      max-height: 100vh;
    }
    

    Live running example: https://jsfiddle.net/resistdesign/szrv5o19/

    0 讨论(0)
  • 2020-12-01 06:31

    I don't know if I'm getting this right, but if you want to set it to 100% oh the height of the viewport, you could easily do this in css:

    .stuff {
      background:#DDD;
      display:inline-block;
      height: 100vh;
      width : 100vh;
    }
    

    You could check it out here

    0 讨论(0)
  • 2020-12-01 06:41

    There is a neat trick using pure css that i stumbled upon:

    #square {
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    }
    

    Hope that helps.

    http://blog.brianjohnsondesign.com/2013/maintain-aspect-ratio-for-html-element-using-only-css-in-a-responsive-design/

    0 讨论(0)
  • 2020-12-01 06:41

    CSS only solution : vh units

    To make the element resize according to the height of the viewport you can use vh units :

    vh : 1/100th of the height of the viewport. [source MDN]


    Example:

    body{margin:0;}
    
    div{
        background:gold;
        height:100vh;
        width:100vh;
    }
    <div></div>

    Fiddle DEMO

    This will make the width and height of the element equal to the height of the viewport.


    Bowser support for vh units is IE9+. More info here

    0 讨论(0)
  • 2020-12-01 06:41

    You could use Javascript and get the screen size. After which you could set width and height accordingly.

    window.screen.width, and window.screen.height should work.

    You could then use this information and generate a tiny bit of CSS for the page to be displayed accordingly.

    0 讨论(0)
  • 2020-12-01 06:49

    You can do this with jquery (or pure javascript if you prefer).

    With jquery:

    <div id="square">
    </div>
    
    $(document).ready(function(){
      var height = $(window).height();
      $('#square').css('height', height);
      $('#square').css('width', height);
    });
    
    0 讨论(0)
提交回复
热议问题