CSS-only square div fitting inside rectangle div

前端 未结 4 610
忘掉有多难
忘掉有多难 2021-01-06 02:54

I have determined how to set a div height based on its width (using percentage width and padding-bottom). But I also need to be able to set a div width based on its height.

4条回答
  •  臣服心动
    2021-01-06 03:04

    This is easiest done when .rectangle literally takes the full window - in other words, its width and height are 100vw and 100vh respectively.

    If that is the case, then your square is simply:

    .square {
        width: 100vh;
        height: 100vh;
        margin: 0 auto;
    }
    @media all and (orientation: portrait) {
        .square {
            width: 100vw;
            height: 100vw;
        }
    }
    

    It may be a little trickier to vertically-center the square in the portrait view, but certainly not impossible. margin-top: calc(50vh - 50vw) would do it, for instance.

提交回复
热议问题