CSS ID变体

时间:2011-05-27 21:08:53

标签: css inheritance position generator

嘿,我猜这可能是相当微不足道的,但我很难找到答案或搞清楚。

我正在尝试创建一个彩色方块网格,它们之间有任意间距。 这本身很容易做到,特别是因为我只需要九个方格。但同时 我看看我完成的代码,我不禁觉得有一种更加简单有效的方法来实现这一目标。

目前,我在css中声明了九个不同的ID,每个方块一个。

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 个答案:

答案 0 :(得分:4)

您可以将一个类用于共享属性的方块:

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

是否有一个特定的原因,你绝对定位他们?听起来像是一个更适合花车的工作。

div.container {
    width: 240px;
}

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

答案 1 :(得分:3)

假设内部正方形为div s,则容器中没有其他div,并且每个内部div应该是相同的width和{{ 1}},这就是我要做的事情:

height

如果每个.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; } .. 都需要单独的topleft属性,那么您别无选择,只能使用div

由于使用了id,您可以避免添加class,这会选择.container > div的直接子项的所有div元素。

HTML看起来像这样:

.container

答案 2 :(得分:1)

为什么不给所有方块赋予相同的类并应用

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

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