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

hug*_*ige 5 css

我知道这个问题:高度等于动态宽度(CSS流体布局)

但我想要更多!! 我想要一个灵活的容器,它总是具有正方形的纵横比,但最大高度和最大宽度为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---
-       -
-       -
-#######-
-#######-
-#######-
-#######-
-       -
-       -
---------
Run Code Online (Sandbox Code Playgroud)

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

编辑: 我知道css3 有calc(),但由于移动浏览器支持不佳,我不想使用它.

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

这就是如何用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

        });
    }
});
Run Code Online (Sandbox Code Playgroud)

hug*_*ige 4

我终于弄明白了。神奇的成分是视口单元。

给定这个 html 结构:

.l-table
  .l-table-cell
    .square
Run Code Online (Sandbox Code Playgroud)

你可以使用这个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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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