Square DIV where height is equal to viewport

前端 未结 8 1310
我在风中等你
我在风中等你 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

    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/

提交回复
热议问题