0

我有这个代码:http: //jsfiddle.net/XXu8G/

我希望元素与脊柱周围的中心对齐。Isotope jQuery 插件有一个类似的功能叫做脊椎对齐: http: //isotope.metafizzy.co/custom-layout-modes/spine-align.html但不幸的是它在每一侧只列出了一个项目。我想在每一边都有多个项目。

如果没有单独的“左”和“右”div,如何实现这些?

4

1 回答 1

2

此代码适用于 CSS3 浏览器(请参阅 fiddle;注意,在 IE8 及以下版本以及其他不支持它的nth-child情况下,必须用每个需要“跳过”脊椎中心的元素上的类替换)。需要成为列表的center-stamp一部分以使其适合我(但请参阅下面的可选解决方案)。

#container {
    width: 380px;
    margin: 0 auto;
    overflow: hidden;
}

#items li#center-stamp { 
    width:100px; 
    height:100px; 
    background:red; 
    margin: 0 -240px 0 140px;
}
#items li { 
    width:50px; 
    height:50px; 
    background:#ccc; 
    margin:10px; 
    float:left; 
    display:block; 
}

#items li:nth-of-type(4n) {
    margin-left: 110px;
}

可选解决方案

如果center-stamp纯粹是展示性的,则可以将其移动到像这样的伪元素(参见小提琴)。

#container {
    width: 380px;
    margin: 0 auto;
    overflow: hidden;
}

#items:before { 
    content: '';
    width:100px; 
    height:100px; 
    background:red; 
    margin: 0 -240px 0 140px;
    float: left;
    display: block;
}
#items li { 
    width:50px; 
    height:50px; 
    background:#ccc; 
    margin:10px; 
    float:left; 
    display:block; 
}

#items li:nth-of-type(4n+3) {
    margin-left: 110px;
}

更“灵活”(仍然是 CSS3)的解决方案

对于灵活宽度和动态元素个数的新需求,假设元素宽度是标准的,还是有纯CSS3的方案。它是通过明智地使用@media查询来完成的(可能最好由 CSS 预处理器(如 LESS 或 SCSS)生成),您需要对查询的范围设置实际限制。这是一个小提琴和其中的css代码:

#container {
    width: 100%;
    overflow: hidden;
}

#center-stamp {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 100px;
    margin-left: -50px;
    background-color: red;
    z-index: -1;
}

#items {
    overflow: hidden;
    width: 240px;
    margin: 0 auto;
}

#items li { 
    width:50px; 
    height:50px; 
    background:#ccc; 
    margin:10px; 
    display: block; 
    float: left;
}

#items > li:nth-child(2n) {
    margin-left: 110px;
}

@media all and (min-width: 380px) {
    #items {
        width: 380px;
    }
    #items > li:nth-child(2n) {
        margin-left: 10px;
    }    
    #items > li:nth-child(4n+3) {
        margin-left: 110px;
    }
}

@media all and (min-width: 520px) {
    #items {
        width: 520px;
    }
    #items > li:nth-child(4n+3) {
        margin-left: 10px;
    }    
    #items > li:nth-child(6n+4) {
        margin-left: 110px;
    }
}

@media all and (min-width: 660px) {
    #items {
        width: 660px;
    }
    #items > li:nth-child(6n+4) {
        margin-left: 10px;
    }    
    #items > li:nth-child(8n+5) {
        margin-left: 110px;
    }
}

注意:关键是将宽度重置为允许的块数,然后覆盖先前宽度的nth-child选择器将其放回10px边距,然后为nth-child.

于 2012-07-24T17:10:12.310 回答