同样重复的课堂风格?

时间:2014-03-27 10:26:51

标签: css

开发时,我通常使用工具集。目前它看起来像这样:

MT10 {margin-top:10px;}
MT20 {margin-top:20px;}
MT30 {margin-top:30px;}
MT40 {margin-top:40px;}

PADB10 {padding-bot:10px;}
PADB20 {padding-bot:20px;}
PADB30 {padding-bot:30px;}
PADB40 {padding-bot:40px;}

是否可以让一个类能够检测到我在MT或PADB之后输入的任何数字?我想象一个泛型类,我可以添加一个数字,这将影响样式。这可能吗?

3 个答案:

答案 0 :(得分:0)

使用纯CSS是不可能的,但是如果你真的想制作动态CSS,你可以创建一个返回CSS文件头和内容的PHP文件,并像普通的外部样式表一样包含它。如果有很多与数据库内容或其他服务器端数据相关的动态因素,我会选择PHP选项。

示例(未经测试)

header("Content-type: text/css");

$prefixes = array('MT' => 'margin-top', 'PADB' => 'padding-bot');
foreach ($prefixes as $prefix_key => $prefix_value) {
    for ($i = 10; $i <= 40; $i += 10) {
        echo $prefix_key.$i.' {'.$prefix_value.':'.$i.'px;}'."\n";
    }
}

如果它不是与内容相关的,并且你想使用CSS框架,你也可以使用CSS框架,如SASS(http://sass-lang.com/)或LessCSS(http://lesscss.org/)。

答案 1 :(得分:0)

使用纯CSS,这是不可能的。

但是,如果您使用类似LessCSS的内容,则可以实现。

例如:

.margin-top(@margin) {
  margin-top: @margin;
}

然后,给每个人一类:

.margin-top(10px);
.margin-top:(20px);

等...

答案 2 :(得分:0)

可以使用Simple Jquery完成 -

<script>
    $(document).ready(function myfunction() { //on document ready
        $("[class^='MT']").each(function (index) {  //select each element which starts with MT.
            var cls = $(this).attr('class');  //get the class of it
            cls = parseInt(cls.substring(2)); // select the substring that has number, here its 2, as the number starts after MT.
            $(this).css("margin-top", cls + "px"); //assign margin-top property to that element
        });

        $("[class^='PADB']").each(function (index) { //select each element which starts with PADB.
            var cls = $(this).attr('class');
            cls = parseInt(cls.substring(4)); // here its four as the number that needs to be selected is after PADB.
            $(this).css("padding-bottom", cls + "px"); // assign padding-bottom property to this element.
        });

    });
</script>

在这里你可以JS FIDDLE DEMO