css - 如何始终使用纯 CSS 在视口(viewport)中居中一个灵活的正方形?

标签 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(甚至更好的跨浏览器)来实现这一点?

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

编辑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

        });
    }
});

最佳答案

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

给定这个 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 .

关于css - 如何始终使用纯 CSS 在视口(viewport)中居中一个灵活的正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824709/

相关文章:

html - 指定 CSS3 列的宽度

image - CSS 图像集/背景图像。 img srcset 的替代方案?有人用这个吗?

javascript - 没有类的 jQuery 翻转容器

css - 向特定行添加悬停颜色

css - 跨浏览器按钮之间的间距不一致?

html - 将 html 图形宽度设置为其包含的图像宽度相同

css - Woocommerce 产品列表间距

css - 文字从左到右出现

css - TinyMCE 代码缩进问题

html - 主 div 内的元素超出宽度