2013-07-07 26 views
1

我正在用rails.编写应用程序我对css还不是很熟悉。虽然,我在努力。而且有一个问题,我的生成HTML标签在css帮助下缩进生成的html div类

<div class="sub-product post-1"> 
// content goes here 
</div> 

<div class="sub-product post-2"> 
// content goes here 
</div> 

<div class="sub-product post-3"> 
// content goes here 
</div> 

<div class="sub-product post-4"> 
// content goes here 
</div> 

现在,你可以看到布置为post有不同的号码。我试图做的是向他们展示缩进,这里是我的CSS

.sub-product.post-1 { 
margin:30px 
} 

它的工作原理,但如果我让.sub-product.post-1.post-2.post-3.post-4它只表示缩进。我想我知道这里错了什么,但是什么是一个优雅的解决方案来显示它们缩进?

谢谢

回答

0

只需添加这些CSS规则:

.sub-product { 
    border: 1px solid gray; 
} 

.post-1 { 
    margin-left: 30px; 
} 

.post-2 { 
    margin-left: 60px; 
} 

.post-3 { 
    margin-left: 90px; 
} 

.post-4 { 
    margin-left: 120px; 
} 

这里有一个DEMO

+0

我想对不同的帖子类型应用不同的边距。 Post-1从开始缩进30px。后2 30多等等,直到4后。 – psharma

+0

我已更新帖子。希望能帮助到你! – leoMestizo

+0

是的,它确实有帮助。有没有其他的方式(更干净的方式来做到这一点)? – psharma

0

这可以通过jQuery整齐地完成。只需将以下代码添加到HTML文档中,并且您可以为任何数量的div执行此操作。

<script> 

//iterate through all divs that have .sub-product class 
$('.sub-product').each(function(){ 

    //save the class of each div in a variable 
    var num = $(this).attr('class'); 

    //fetch just the number from each classname 
    num = num.replace('sub-product post-', ''); 

    //change the margin-left of each div based on its class number 
    $(this).css({ 
     marginLeft: num*30+'px' 
    }); 
}); 
</script> 

工作例如:http://jsfiddle.net/Tv347/11/

否则,如果你严格要使用CSS,你最好的选择将是应用样式到个人的div像这样:

.post-1{ 
    margin-left:30px 
} 

.post-2{ 
    margin-left:60px 
} 

.post-3{ 
    margin-left:90px 
} 

.post-4{ 
    margin-left:120px 
} 
+0

我想对不同的帖子类型应用不同的页边距。 Post-1从开始缩进30px。后2 30多等等,直到4后。 – psharma

+0

我已经提供了一个JavaScript解决方案,将普遍照顾您的任何数量的div :) – soundswaste

1

你可以嵌套你post-*的div作出更加明确他们有父子关系(至少这是根据您的文章我假设):

<div class="sub-product post-1"> 
// content goes here 
    <div class="sub-product post-2"> 
    // content goes here 
     <div class="sub-product post-3"> 
     // content goes here 
      <div class="sub-product post-4"> 
       // content goes here 
      </div> 
     </div> 
    </div> 
</div> 

这样你就只需要以下CSS:

.sub-product[class^=post-] { // class starts with post- 
    margin-left: 30px; 
}