开发者

beginner's question about CSS

I am creating a website and i want to allow personalization to individual users upto some extent like changing font family, background color etc. The problem with this is that, my default css file that i load has already default classes for everything. No开发者_StackOverfloww when i fetch the background color from my database, then if there is null value for background color then default css class of mystylesheet.css should be loaded and if the value is not null, then i want to override this with my default css. How is it possible? Thanks in advance :)


Load the default stylesheat in a style tag, and put your dynamic styles in a style tag after that.

Which style to use when different styles target the same element is determined by specificity, and if the selectors are the same, by order. The style that is found last is used.


The approach mentioned by zaf would require that you reload the page when you want to switch styles sheets. What I find to be a better approach is to add a classname to the body if you have the option of using javascript

<body class="theme-1">
  <div class="main"><div>
</body>

Then each of your style sheets should contain the theme name in the declarations:

--theme1.css

.theme-1 div.main {
  background-color: #eee
}

--theme2.css

.theme-2 div.main {
  background-color: #f30
}

To switch style sheets, you just remove the old theme name and add the theme you want to use.

Then you can even add style sheets dynamically if you provide an interface for the user to customize the look and feel of your page.

New Improved Answer:

I just found a nice solution implemented by the folks at extjs. It involves loading all the stylesheets you want using <link> tags. The trick is that you can set a disabled property on the link element which will cause it not to apply.

For an example, use firebug and look at

http://www.extjs.com/deploy/dev/examples/themes/index.html

Look for styleswitcher.js and look at the function setActiveStyleSheet

function setActiveStyleSheet(title) {
  var i,
     a,
     links = document.getElementsByTagName("link"),
     len = links.length;

  for (i = 0; i < len; i++) {
    a = links[i];
    if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if (a.getAttribute("title") == title) a.disabled = false;
    }
  }
} 


EDIT: Reason for CSS property precedence?

One way is to produce the css file dynamically from a php script.

You would include the file like:

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

And the css.php file would look something like this:

<?php
header('Content-type: text/css');
// whatever you want to ouput depending on the user
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜