<link rel="stylesheet" type="text/css" href="reset.css" />
<style type="text/css">
body { position: relative; }
.contain { position:relative; overflow: hidden; width: 80%; height: 100%; margin: 0 auto; }
.box {
background-color: #F0F0F0;
color: #888;
font-family: Arial, Tahoma, serif;
font-size: 13px; }
.box p { padding: 10px; }
.box span {
float: left;
font-size: 26px;
font-weight: bold; }
div.alt { background-color: #CCC; }
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var myFluidGrid = {
COLNUMBER : 2, // Minimum column number.
COLMARGIN : 10, // Margin (in pixel) between columns/boxes.
COLWIDTH : 240, // Fixed width of all columns.
doLayout : function() {
var self = this;
var pointer = 0;
var arr = [];
var columns = Math.max(this.COLNUMBER, parseInt($('body').innerWidth() / (this.COLWIDTH + this.COLMARGIN)));
$('.box').css('position', 'absolute').css('width', this.COLWIDTH + 'px');
$('.box').each(function() {
var tempLeft = (pointer * (self.COLWIDTH + self.COLMARGIN));
$(this).css('left', tempLeft + 'px');
var tempTop = 0;
if (arr[pointer]) { tempTop = arr[pointer]; }
$(this).css('top', tempTop + 'px');
arr[pointer] = tempTop + $(this).outerHeight() + self.COLMARGIN;
pointer++;
if (pointer === columns) { pointer = 0; }
});
}
};
$(window).ready(function() {
myFluidGrid.doLayout();
}).resize(function() {
myFluidGrid.doLayout();
});
</script>
<div class="contain">
<div class="box">This is box number 1...</div>
<div class="box">This is box number 2...</div>
<div class="box">This is box number 3...</div>
</div>
当前代码的演示:http://grahamthomas.me/temp/test.html
尝试使上面的网格无论其大小如何都保持在窗口中心。我目前大致居中,但是当调整窗口大小时,居中变得不真实,直到新列填充内容(即动态网格在列之间 - 大于3列,但不是4列)。 / p>
我不擅长JS,但我的逻辑是:
当拖动窗口较小时,您可以清楚地看到溢出:隐藏属性“跳过”最右侧的框。我假设,窗口宽度没有正确计算。我尝试了var列的变体,例如:
var columns = Math.max(this.COLNUMBER, parseInt(($('body').innerWidth() * 0.8)/ (this.COLWIDTH + this.COLMARGIN)));
..它将列保持在窗口内,但仍然不是一个合适的中心。
我一直在看这个问题,有人有什么想法吗?
由于
答案 0 :(得分:0)
无需JavaScript:
<html>
<head>
<style>
body {
text-align: center;
}
div.main {
position: absolute;
top: 100px;
left: 50%;
margin-left: -40%;
width: 80%;
}
div.main div.block {
height: 180px;
width: 180px;
background: #a00;
float: right;
margin: 10px;
}
</style>
</head>
<body>
<div class="main">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
</body>
</html>