User defined CSS / Styles - asp.net

We are looking into providing users of our application the ability override the default site CSS.
Currently they can choose a site theme but it would be nice to allow them to change properties such as background color, font color, font face etc.
I'm torn between giving each site a "user defined" stylesheet that can be edited from the administration area or providing some kind of CSS builder.
The first option provides the most flexibility but could also be the most problematic and requires the user to have some basic understanding of CSS.
So aside from the obvious, (which is the best solution?) I have a few additional questions:
User Defined Css:
Is there a web based CSS editor available?
Is there a server side (.net) CSS validator available (for verifying the css the user enters)
Css Builder:
Is there a web based CSS builder already available?
What is the best way of generating the CSS based on the rules provided by the user (I thought about using some kind of templating engine to do this (NVelocity, Razor etc.)?
Thanks
Solution
I've added an answer below with the solution we went for.

however never used, recently I looked at Brosho Design in the Browser jQuery Plugin
With this Plugin you can style your
markup right in your browser with a
build-in element selector and CSS
editor. Generate the CSS code of
altered elements with one click and
use it in your own stylesheet.
demo here

I'd recommend to build a custom css editor since it's the easiest way to limit which elements and attributes the user will be able to edit / customize, and how. Just keep it simple and you will do just fine.
To validate CSS you could use the API of the W3 CSS Validator, http://jigsaw.w3.org/css-validator/api.html

I've built an application that does exactly this. It's a little more involved as there are multiple master pages and themes, and the user can attach custom urls to load themes - example: /someclienturl would load a specific theme.
Anyway, here's the schema I used. One thing I wish I added is the ability for power users to add custom styles to the stylesheet that's eventually written. Basically, a theme section would apply to a selector #header, for example. And ThemeSectionCssStyle holds user added customizations for that selector. If you have any more questions let me know. It ended up being a fairly involved sub-project. I'm curious to see what anyone else came up with.

I think the key factor here is whether you want your users to 'play with the codez'
If you do then something like this (posted by #Caspar) can be helpful in generating the css. If you do allow direct access to the css then the W3 CSS Validator (posted by #Trikks) is definitely necessary.
In my case I didn't want to provide direct access to the Css. Looking around at various sites that allow you to change simple style properties (background-color, font-face, color etc.) it seems that they have just created their own interfaces for this. There are plenty of javascript plugins around for making this process quite slick (color pickers etc.).
Once you have the styles stored somewhere you need some way of rendering them out.
I couldn't find any .net Css writers. I think it may be possible in Less but the solution was quite simple just using what's built into asp.net mvc.
I created a Css action result (courtesy of #Darin Dimitrov):
public class CssResult : PartialViewResult {
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.ContentType = "text/css";
base.ExecuteResult(context);
}
}
Then in my controller (a simple example):
[HttpGet]
public ActionResult Index()
{
var styles = new Dictionary<string, string>()
{
{ "color", "red" },
{ "font-family", "Consolas, Courier, Serif" },
{ "font-size" , "12px" }
};
return this.Css(styles);
}
Then my view (views/css/index.cshtml):
body {#foreach (var item in Model) {
#string.Format("{0}: {1};", item.Key, item.Value)
}
}
This will essentially render out the styles in the passed in dictionary. Of course you may want to create a specific class for holding these styles so that you could also specify the dom element name/class/id.
Finally to render out the stylesheet on our page we can call Url.Action("index", "css").

Related

What does "property=''" do?

I'm working on a Drupal site/theme. The CSS and PHP modifications are fairly easy; they just take a little time to learn and get working exactly how I want.
However, I'm having issues applying CSS styles to some elements because of what I think is a property function.
The code looks like <h2 property="dc:title" datatype="" class="node-title">.
What is a property function and what does it do or control within the page? Also how can I modify or remove it?
It's not a property function; it's an attribute that is used from RDFa, and that is added from the RDF module.
The easier way to remove those attributes is to disable the module, but I would not suggest doing it, as the purpose of that module is to enrich your content with metadata to let other applications better understand its relationships and attributes.
Alternatively, if the problem is just with that property, used for the nodes, then you can implement code similar to the following one:
function mymodule_preprocess_node(&$variables) {
if (isset($variables['title_attributes_array'])) {
$variables['title_attributes_array']['property'] = NULL;
}
}
The module should be executed after the RDF module, to allow its hook to be executed after the one implemented by the RDF module.
I have not seen any compatibility problem between the attributes added by the RDF module and the JavaScript code executed by Drupal core or third-party modules. It would probably be the case to investigate why you are having problems with the JavaScript code when those HTML attributes are added.
in your css file, put:
h2[property="dc:title"]{color:#FFFFFF;}
or if it is a link, you may need:
h2[property="dc:title"] a {color:#FFFFFF;}
From wikipedia, check out RDFa
RDFa (or Resource Description
Framework – in – attributes) is a W3C
Recommendation that adds a set of
attribute-level extensions to XHTML
for embedding rich metadata within Web
documents.
It is basically a way to add more metadata to XHTML docs for better semantics.

Is there a way to have a CSS selector apply to a specific host? (For my custom browser stylesheet.)

I want to apply styles (edit:in my browser's user-defined stylesheet, a local file on my machine that let's me customize how other people's websites render for me) to a specific site, but the selectors on many web pages are often generic (and obviously out of my control, since they're not my websites.)
If I have to use very general selectors (eg. #box) to customize a given website, that style might unintentionally affect other websites that have that same generic selector. Is there a way to specify a domain with a selector so I can my custom styles for each website separate?
I also found #-moz-document which looks good, but is Mozilla-specific and I use a WebKit browser. Is there an equivalent?
#-moz-document url(https://www.example.com/decrypt.php) {
Is the CSS hosted on a server that also allows you to script? Have you tried writing a server-side script to generate the correct CSS rules depending on the host that's serving the page?
Edit added March 30 2010:
You might be better off using the Greasemonkey extension to do this. It's far more powerful than user-defined stylesheets since you can use JavaScript, and adding domain or page-specific rules is as easy as adding special tags to the comments in the header. Greasemonkey was made specifically for handling your type of problem, and while you need a plugin to run Greasemonkey scripts in Firefox, Chrome ships with Greasemonkey support built-in.
If you can modify the HTML using javascript, there would be a way. It could go something like this (using JQuery):
var hostId = // detect the id of the host
var highLevelElement = $("body"); // or a different element that holds everything
highLevelElement.attr("id", hostId);
Then, in your CSS, you can do this:
#Mozilla div.Whatever { background-color: orange; }
#IE6 div.Whatever { background-color: red; }
#IE9 div.Whatever { background-color: green; }
// etc.
Consider installing an ad blocker such as uBlockOrigin, then writing some custom filters. You can add these custom filters in Settings -> My Filters.
examplewebsite.com###ExampleId, .ExampleClass:style(background-color: yellow !important;)
Uhm, I think php would be the most rational solution, and actually very easy.
Use php to decide what/when to do and echo certain css files in certain cases.
If you need more help, tell us more about your problem and I'll write the complete solution for you.

What's the best way to link to an external style sheet in SharePoint

I have some user controls that I'm loading in SharePoint and I would prefer to have all those styles contained in an external style sheet. What's the best way to link to an external stylesheet in CSS?
Thanks.
Can you not add a <link rel...> to the head? If not, can you this.page.header.controls.add?
This code will ensure that you only add 1 stylesheet reference to a page regardless of how many web parts you have on it - same code snippet can be used for javascript.
protected override void OnPreRender(EventArgs e)
{
const string stylesheet = "YourStylesheet.css";
if (!Page.IsClientScriptBlockRegistered(stylesheet))
{
Page.RegisterClientScriptBlock(stylesheet,
string.Format(#"<link href=""{0}/{1}"" rel=""stylesheet""/>",
this.ClassResourcePath, stylesheet));
}
base.OnPreRender(e);
}
Thanks,
I was looking at that way too complicated like. Your answer solved my problem and will actually work a lot better than the method that I was going to approach it from.
If you're using MOSS, you can remove this configuration from your code entirely by using SharePoint's built in alternate style sheet property.
Drop down the Site Actions menu, and select Site Settings->Modify All Site Settings.
On the resulting page, click on the Master page link in the Look and Feel column.
On the Site Master Page Settings page, scroll to the bottom to the Alternate CSS URL section. Select the Specify a CSS file... radio button and enter the URL of your style sheet. I put mine in the Home site's Style Library, but you can pretty much put it where you want.
If you like, you can set it for all the subsites to by selecting the Reset all subsites to inherit this alternate CSS URL checkbox.
Click the OK button.
Sadly,this configuration isn't available for WSS sites. But the object model does have it. So you can apply it with code in both WSS and MOSS, either in a web part or via something like PowerShell.
In code, once you have a reference to the the SPWeb object, say in a cleverly named variable called theWeb, you can just assign the URL of stylesheet with the following code:
theWeb.AlternateCssUrl = "http://server/site/library/stylesheet.css";
theWeb.Update();

Preferred method for linking to stylesheets from a UserControl?

We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.
So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think.
Does anyone have any preferred methods, and if so, what and why?
I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.
It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.
This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.
Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it.
When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.
What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.
I could use #import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?
If you're determined to do it yourself, here's some code from the CssFriendly project that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.
string filePath = page.ClientScript.GetWebResourceUrl(type, css);
// if filePath is not empty, embedded CSS exists -- register it
if (!String.IsNullOrEmpty(filePath))
{
if (!Helpers.HeadContainsLinkHref(page, filePath))
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(filePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}
}
I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.
Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.
It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.
If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme.
But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).
In either case, don't forget to set the CssClass attribute on your controls.
To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.
If you have a module called "30DayPricingCalc" then you could name the classes/id's:
30DayPricingCalc.css
.30daypricingcalc_main_content
{
...
}
Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.
Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the #import tag.
Cheers!

How do you dynamically load a CSS file into a Flex application?

I know that you can apply CSS in order to style objects in Flex using the StyleManager:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html
You can also load compiled CSS files (SWFs) dynamically:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html
However, I'm dynamically creating my CSS files using a web GUI and a server-side script.
If the CSS is changed, then the script would also need to compile the CSS into an SWF (which is not a viable option). Is there any way around this?
In this comment to an issue related to this in the Adobe bug tracker T. Busser is describing what might be a viable solution for you:
"I've created a small class that will 'parse' a CSS file read with an
HTTPService object. It takes apart the
string that is returned by the
HTTPService object, break it down into
selectors, and create a new
CSSStyleDeclaration object for each
selector that is found. Once all the
properties are assigned to the
CSSStyleDeclaration object it's added
to the StyleManager. It doesn't
perform any checks, you should make
sure the CSS file is well formed, but
it will be sufficient 99% of the time.
Stuff like #font, Embed() and
ClassReference() will hardly be used
by my customers. They do need the
ability to change colors and stuff
like that so they can easily theme the
Flex application to their house
style."
You could either try to contact this person for their solution or alternatively maybe use the code from this as3csslib project as a basis for writing something like what they're describing.
You can also implement dynamic stylesheet in flex like this . Here i found this article :
http://askmeflash.com/article_m.php?p=article&id=6
Edit: This solution does not work. All selectors that are taken out of the parser are converted to lowercase. This may work for your application but it will probably not...
I am leaving this answer here because it may help some people looking for a solution and warn others of the limitations of this method.
See my question: "Looking for CSS parser written in AS3" for a complete discussion but I found a CSS parser hidden inside the standard libraries. Here is how you can use it:
public function extractFromStyleSheet(css:String):void {
// Create a StyleSheet Object
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(css);
// Iterate through the selector objects
var selectorNames:Array = styleSheet.styleNames;
for(var i:int=0; i<selectorNames.length; i++){
// Do something with each selector
trace("Selector: "+selelectorNames[i];
var properties:Object = styleSheet.getStyle(selectorNames[i]);
for (var property:String in properties){
// Do something with each property in the selector
trace("\t"+property+" -> "+properties[property]+"\n");
}
}
}
You can then apply the styles using:
cssStyle = new CSSStyleDeclaration();
cssStyle.setStyle("color", "<valid color>);
FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration("Button", cssStyle, true);
The application of CSS in Flex is handled on the server side at compilation and not on the client side at run time.
I would see two options then for you (I'm not sure how practical either are):
Use a server side script to compile your CSS as a SWF then load them dynamically.
Parse a CSS Style sheet and use the setStyle functions in flex to apply the styles. An similar example to this approach is the Flex Style Explorer where you can check out the source.
Good luck.

Resources