2011-05-27 36 views
3

嘿,我猜这可能是相当微不足道的,但我很难找到答案或找出答案。CSS ID变化

我想创建一个网格,它们之间有任意间距的彩色方块。 这本身很容易做到,特别是因为我只需要九个方格。但是,虽然我看着我完成的代码,但我不禁感到有一种更加简单高效的方法来实现这一点。

此刻,我有九个不同的ID在我的CSS中声明,每个正方形一个。

div.container{ 
    position:relative; 
    left:50px; 
    top:50px; 
    background-color:rgb(45,45,45); 
    height:300px; 
    width:300px; 
} 

#square{ 
    position:absolute; 
    background-color:rgb(52,82,222); 
    left:20px; 
    top:20px; 
    height:80px 
    width:80px 

#square2{ 
    position:absolute; 
    background-color:rgb(58,82,22); 
    left:110px; 
    top:20px; 
    height:80px; 
    width:80px; 


etc etc etc 

我想要做的是找到一个更有效的方法来做到这一点。

感谢您的帮助!

回答

3

假设内部正方形是div S,没有其他div是你的容器内,并且每个内部div应该是相同的widthheight,这是我会怎么做:

.container { 
    position: relative; 
    left: 50px; 
    top: 50px; 
    background: rgb(45,45,45); 
    height: 300px; 
    width: 300px; 
} 
.container > div { 
    position: absolute; 
    background-color: rgb(52,82,222); 
    height: 80px; 
    width: 80px; 
} 

#square1 { 
    left: 20px; 
    top: 20px; 
} 
#square2 { 
    left: 110px; 
    top: 20px; 
} 
.. 

如果您需要对每个div单独使用topleft属性,则您别无选择,只能使用id s。

你可以避免到class感谢添加到使用.container > div,将选择所有div元素是.container直接孩子。

的HTML应该是这样的:

<div class="container"> 
    <div id="square1"></div> 
    <div id="square2"></div> 
    .. 
</div> 
+0

如果我在广场内包含div,该怎么办? '.container> div'也会影响这些吗?或者他们不是直接的孩子? – danem 2011-05-27 21:53:07

+1

'.container> div'不会影响那些。 ['>'是直接的子选择器。](http://reference.sitepoint.com/css/childselector)我很努力地在这里解释它:[http://jsfiddle.net/Mgk23/]( http://jsfiddle.net/Mgk23/) – thirtydot 2011-05-27 21:55:04

4

您可以使用类共享特性广场:

.square { 
    position: absolute; 
    width: 80px; 
    height: 80px; 
} 

有没有什么是绝对定位它们虽然具体的原因是什么?听起来像一个更适合花车的工作。

div.container { 
    width: 240px; 
} 

.square { 
    float: left; 
    width: 80px; 
    height: 80px; 
} 
+0

我在想同样的事情,你打我吧。 – 2011-05-27 21:17:00

+0

没有理由特别哈哈。我想它只是我可怜的CSS技能的证据:P 然而,我对你的答案感到困惑的是我如何声明后续的方块,以便它们继承这些常量。我正在考虑像OOP这样的事情,但似乎我不能用这种方式来解决这个问题。谢谢你和我在一起! – danem 2011-05-27 21:50:20

1

为什么不把所有的方块同一类和应用类似

.square 
{ 
    display: inline-block; 
    width: 80px; 
    height: 80px; 
    zoom: 1; 
    *display: inline /* for IE */ 
} 

这应该使所有块的包装很好,而不必为每个人添加样式。