如何使用纯CSS始终在视口中居中灵活的方块?

我知道这个问题:Height equal to dynamic width (CSS fluid layout)

但我想要更多!!我想要一个灵活的容器,它总是具有正方形的纵横比,但最大高度和最大宽度为100%的页面(窗口元素),并且在其顶部始终垂直和水平居中.

像这样:

// Container matches height of the window
// container-height = 100%; container-width = absolute-container-height
-page/browser-window-
-      #######      -
-      #cont-#      -
-      #ainer#      -
-      #######      -
---------------------


// container matches width of the window
// container-width = 100%;  container-height = absolute-container-width
--page---
-       -
-       -
-#######-
-#######-
-#######-
-#######-
-       -
-       -
---------

是否有可能用纯css(甚至更好的跨浏览器)实现这一点?

编辑:
我知道css3有calc(),但由于poor mobile browser-support,我不想使用它.

EDIT2:
好像,我没有让自己清楚.我需要包装器的高度和宽度来匹配窗口的高度或宽度,具体取决于哪个更小.方形容器不应超过窗口高度/宽度的较小值.

这就是如何用jQuery完成的:

 // container/#main-wrapper has top: 50%,left: 50%,position: absolute  via css  
 $(window).resize(function () {
    var $ww = $(window).width();
    var $wh = $(window).height();

    if ($ww > $wh) {
        $('#main-wrapper').css({
            height: $wh,width: $wh,marginTop : ($wh / 2) * -1,marginLeft : ($wh / 2) * -1
        });
    } else {
        $('#main-wrapper').css({
            height: $ww,width: $ww,marginTop : ($ww / 2) * -1,marginLeft : ($ww / 2) * -1

        });
    }
});
最佳答案
我终于弄明白了.神奇的成分是视口单元.

鉴于这个html结构:

.l-table
  .l-table-cell
    .square

你可以使用这个css(很好地实现它的scss,但你明白了)让它工作

html,body{
  height: 100%
}
l-table{
  background: orange;
  display: table;
  height: 100%; 
  width: 100%;
}
.l-table-cell{
  display: table-cell;
  vertical-align: middle;
  border: 2px solid black;
}
.square{
  background: red;
  margin: auto;
  @media (orientation:landscape) {
    width: 70vh;
    height: 70vh;
  }
  @media screen and (orientation:portrait) {
    width: 70vw;
    height: 70vw;
  }
}

http://codepen.io/johannesjo/pen/rvFxJ

对于那些需要它的人,有一个polyfill.

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效