css - 左浮动 div 之间的动态边距(或边距模拟)

标签 css css-float

我有一些 div 向左浮动。调整浏览器大小时,它们会根据线上可以容纳的数量上下移动。我想知道是否有一种方法可以动态地(使用 css)让这些 div 以某种方式对齐(或有边距),使它们总是通过调整 marhin 的大小来填充整个屏幕空间?换句话说,当浏览器调整大小时,它们之间的边距会调整大小,但只要另一个 div 可以适应,它就会被添加到行中,或者如果达到并通过了最小边距,另一个 div 将转到下一行,同时边距再次扩大。这是一个例子,现在如何,调整窗口大小以查看我想要“填充”的剩余空间

<html>
<head>
<style>
.test {
float:left;
width: 100px; 
height:100px;
background-color: grey;
margin: 0 10px 10px 0;
}
</style>
</head>
<body>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</body>
</html>

最佳答案

这个问题我见过几次,结果似乎总是 css 不(还)支持元素在动态宽度上的分布。那里有黑客,但老实说,我认为解决这个问题的最快方法是使用 javascript 进行定位。

像这样的东西(写在 prototype 库中)应该做你想做的:

$(document).observe('dom:loaded',function(){
    spaceSquares();
});
window.onresize = function(){spaceSquares();}
function spaceSquares(){
    // this is the minimum margin per square.
    var minMargin = 20;
    // this tells you how many squares will fit on the top row
    var topRowSquares = Math.floor(document.viewport.getWidth() / ($$('.test')[0].getWidth()+minMargin));
    // this will tell you how much space is left over
    var remainderWidth = document.viewport.getWidth() - (($$('.test')[0].getWidth()+minMargin)*topRowSquares);
    // this will tell you how much margin to put on each item
    var marginWidth = (remainderWidth / topRowSquares) + minMargin;
    // this will put the margin on the top row
    for(var i=0;i<topRowSquares;i++){
        $$('.test')[i].setStyle({'margin-left':marginWidth/2+'px','margin-right':marginWidth/2+'px'});
    }
}

我确信有更优雅的方法可以做到这一点,但本质上我只是计算剩余空间并将其划分到正方形之间。我在观察者中包装了对该函数的第一次调用,这样它就不会在加载 dom 之前尝试触发,我在 window.onresize 事件上调用它,这样如果你调整窗口大小,它将始终保持顶行完美分布。

希望这能让您朝着正确的方向前进!

关于css - 左浮动 div 之间的动态边距(或边距模拟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4560709/

相关文章:

html - 字体下拉箭头不显示

html - 有什么方法可以将一些样式繁多的 HTML 与网站的其余样式隔离开来?

html - 使用 CSS 将链接到文本短语的符号放置到文档的边距中

html - CSS显示网格图像问题

javascript - 在 orientationchange 事件后调整 div 的大小/位置

html - 高度百分比值在 Edge 中不起作用

javascript - 如何防止电子邮件地址的 css 自动断字

html - 为什么我的 float 元素在 40% + 60% 宽度设置下不能正常工作?

css - 溢出时保持div彼此相邻 float