我知道这个问题: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/