首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在css的帮助下缩进生成的html div类

在css的帮助下缩进生成的html div类
EN

Stack Overflow用户
提问于 2013-07-08 03:00:19
回答 3查看 146关注 0票数 1

我正在用rails.写一个应用程序,我对css还不是很熟悉。不过,我正在努力。并有一个问题,我生成的html标记是

代码语言:javascript
复制
<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

代码语言:javascript
复制
.sub-product.post-1 {
margin:30px
}

它可以工作,但如果我把它设为.sub-product.post-1.post-2.post-3.post-4,它确实会显示缩进。我想我知道这里有什么问题,但是有什么优雅的解决方案来显示缩进呢?

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-07-08 03:07:00

只需添加以下CSS规则:

代码语言:javascript
复制
.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
EN

Stack Overflow用户

发布于 2013-07-08 04:19:27

您可以嵌套您的post-* div,以更清楚地表明它们具有父子关系(至少我基于您的帖子是这样假设的):

代码语言:javascript
复制
<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:

代码语言:javascript
复制
.sub-product[class^=post-] { // class starts with post-
    margin-left: 30px;
}
票数 1
EN

Stack Overflow用户

发布于 2013-07-08 03:04:41

这可以通过jQuery很方便地完成。只需将以下代码添加到HTML文档中,您就可以对任意数量的div执行此操作。

代码语言:javascript
复制
<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,如下所示:

代码语言:javascript
复制
.post-1{
    margin-left:30px
}

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

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

.post-4{
    margin-left:120px
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17515279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档