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

前端之家收集整理的这篇文章主要介绍了如何使用纯CSS始终在视口中居中灵活的方块?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

像这样:

  1. // Container matches height of the window
  2. // container-height = 100%; container-width = absolute-container-height
  3. -page/browser-window-
  4. - ####### -
  5. - #cont-# -
  6. - #ainer# -
  7. - ####### -
  8. ---------------------
  9. // container matches width of the window
  10. // container-width = 100%; container-height = absolute-container-width
  11. --page---
  12. - -
  13. - -
  14. -#######-
  15. -#######-
  16. -#######-
  17. -#######-
  18. - -
  19. - -
  20. ---------

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

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

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

这就是如何用jQuery完成的:

  1. // container/#main-wrapper has top: 50%,left: 50%,position: absolute via css
  2. $(window).resize(function () {
  3. var $ww = $(window).width();
  4. var $wh = $(window).height();
  5. if ($ww > $wh) {
  6. $('#main-wrapper').css({
  7. height: $wh,width: $wh,marginTop : ($wh / 2) * -1,marginLeft : ($wh / 2) * -1
  8. });
  9. } else {
  10. $('#main-wrapper').css({
  11. height: $ww,width: $ww,marginTop : ($ww / 2) * -1,marginLeft : ($ww / 2) * -1
  12. });
  13. }
  14. });
最佳答案
我终于弄明白了.神奇的成分是视口单元.

鉴于这个html结构:

  1. .l-table
  2. .l-table-cell
  3. .square

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

  1. html,body{
  2. height: 100%
  3. }
  4. l-table{
  5. background: orange;
  6. display: table;
  7. height: 100%;
  8. width: 100%;
  9. }
  10. .l-table-cell{
  11. display: table-cell;
  12. vertical-align: middle;
  13. border: 2px solid black;
  14. }
  15. .square{
  16. background: red;
  17. margin: auto;
  18. @media (orientation:landscape) {
  19. width: 70vh;
  20. height: 70vh;
  21. }
  22. @media screen and (orientation:portrait) {
  23. width: 70vw;
  24. height: 70vw;
  25. }
  26. }

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

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

猜你在找的CSS相关文章