我正在用rails.写一个应用程序,我对css还不是很熟悉。不过,我正在努力。并有一个问题,我生成的html标记是
<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,它确实会显示缩进。我想我知道这里有什么问题,但是有什么优雅的解决方案来显示缩进呢?
谢谢
发布于 2013-07-08 03:07:00
只需添加以下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
发布于 2013-07-08 04:19:27
您可以嵌套您的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;
}发布于 2013-07-08 03:04:41
这可以通过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
}https://stackoverflow.com/questions/17515279
复制相似问题