简体   繁体   中英

How can I create CSS styles dynamically?

In this jQuery example: http://jqueryui.com/demos/sortable/#empty-lists , they have CSS tags for each of the sortable ul's (sortable1, 2, and 3) like so:

CSS

#sortable1 li, #sortable2 li, #sortable3 li { 
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}​

HTML

<div class="demo">

<ul id="sortable1" class='droptrue'>
    (...)
</ul>

<ul id="sortable2" class='dropfalse'>
    (...)
</ul>

<ul id="sortable3" class='droptrue'>
</ul>

The problem I'm having is that in my web page, I don't know ahead of time how many ul's i'll have. What's the best way to handle this without defining a every iteration of #sortable?

You actually don't need to use separate ids for the CSS, you can use a single class instead:

CSS

.sortable li { 
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}​

HTML

<div class="demo">

<ul id="sortable1" class='sortable droptrue'>
    (...)
</ul>

<ul id="sortable2" class='sortable dropfalse'>
    (...)
</ul>

<ul id="sortable3" class='sortable droptrue'>
</ul>

The droptrue and dropfalse classes will still also work as expected.

People seem to be forgetting the simple CSS3 method:

ul[id^=sortable] li {
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}

We use the Attribute Starts With selector here. So this applies styling to any li elements inside any ul whose id attribute starts with the term sortable .

Example .

@AndrewBarber's answer is the better way to approach things, but for the record, you can create CSS dynamically.

What you need to do is use some kind of server-side language (PHP is most popular, for whatever that's worth; ASP.NET, JSP, etc. are also used) to generate the CSS on the fly.

For example, you could use this HTML:

<link rel="stylesheet" type="text/css" href="stylesheet.php">

And then have this for stylesheet.php :

<?php
    header('Content-Type: text/css');
    for ( $i = 1; $i < $sortableMax; ++$i )
    {
        echo <<<EOT
#sortable$i
{
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
EOT;
    }
?>

This produces the following CSS, assuming $sortableMax was somehow set to 5 :

#sortable1
{
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
#sortable2
{
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
#sortable3
{
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}
#sortable4
{
    margin: 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM