Search

Rss Posts

Rss Comments

Login

 


5+ Best Review & Ratings Plugins for WordPress

Jun 22

1. GD Star Ratings

http://www.gdstarrating.com

2. Star Rating for Reviews

http://www.channel-ai.com/blog/plugins/star-rating/

3. Xavin鈥檚 Review Ratings

http://wordpress.org/extend/plugins/xavins-review-ratings/

4. WP-PostRatings

http://wordpress.org/extend/plugins/wp-postratings/

5. WPReviewEngine

http://www.wpreviewengine.com/

6. My Review Plugin

http://www.myreviewplugin.com

7. WPReviewSite

http://www.wpreviewsite.com

25+ Best Premium Skins for vBulletin

Jun 22

vBulletin is one of most popular forum software used over by many websites running discussion forums. Many forums owners feel the need for nice professional and stylish vbulletin skins to customize their sites.  Being a forum owner myself, i have been searching all around for some of the best premium skins for vbulletin. The following are some the beautiful premium vbulletin skins which i really like a lot.

Hexcell Style

Paradise

Aria Style

ChatFusion

Developers Cafe

Blue Demon

Make Money

Red Carbon

Color Theory

Mirage

Animated Arena

Circular

Eye Easy

Orange Theme

Pulse

Maestro

Webspeak

Carribean Breeze

Lustrous

Keepup Fashion

ZoomTube

Funky Fresh

Dash

Imagize

MintyFresh

Enlighten

Creative Creature

Ogenzen

Fundamental

Rough Stuff

Aqueous

Firestorm

Displaying HTML code in WordPress Posts!

Jun 22

I had a terrible problem for a long time which frustrated me quite often! Being a programmer myself i wanted to post html code on my wordpress post and everytime i do it wordpress wont show the code and only shows the html output.

Just like html i wanted to post code like various other programming languages like PHP, CSS and javascript as well. i finally somehow resolved my problem by installing the free wordpress plugin syntax-highlighter. The code looked beautiful once i installed this plugin.

All you have to do is wrap it under the tag

Damn! i love this code syntax highlighter!

How to design 3 Column Website Layout with Top Navigation Menu in CSS

Jun 22

CSS as we go deeper and deeper it gets harder and harder to understand, especially margins, padding and floats could be confusing at times as well. I am going to post here the tutorial to make a very simple CSS website layout (skeleton) with

- Container
- Header
-Top Navigation Menu
- Left Navigation Menu
- Right Navigation menu
- Content Part
- Footer

All elegantly stacked one by one with divs and with css stylesheet. This is a very basic skeleton. The most important css code are highlighted in the picture. The basic concept is shown below.

Code Flow
Notice carefully the div stacked. A container holds all those header, content, and menus.

01 <div id=container>
02       <div id="header">
03         <h2>Header</h2>
04       </div>
05     <div id="topnav-container">
06         <ul id="topnav">
07         <li> <a href="#">Home</a> </li>
08         <li> <a href="#">Categories</a> </li>
09         <li> <a href="#">Services</a> </li>
10         <li> <a href="#">About us</a> </li>
11         <li> <a href="#">Contact us</a> </li>
12         </ul>
13     </div>
14      <div id="leftnav">
15       This is a left navigation bar.
16       This is a left navigation bar
17       This is a left navigation bar
18      </div>
19      <div id="rightnav">
20       This is a right navigation bar
21      </div>
22      <div id="content">
23          <p>
24 Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam
25 </p>
26      </div>
27      <div id="footer">
28         <h2>Footer</h2>
29      </div>
30    </div>

CSS Code

The CSS code is shown below for the above skeleton.

01 #container {
02     margin: 10px auto;
03     width: 95%;
04     border: 1px solid gray;
05 }
06 #header {
07     padding: 3px;
08     border-bottom: 1px solid gray;
09 }
10 #topnav-container {
11 border-bottom: 1px solid gray;
12 padding: 4px 0;
13 background: #e0e0e0;
14 }
15   
16 #topnav {
17 margin:0;
18 padding: 0;
19 }
20   
21 #topnav li  {
22     display: inline;
23    list-style: none;
24   
25 }
26 #topnav li a {
27   
28     text-decoration: none;
29     padding: 0px 5px;
30     color: #333;
31   
32 }
33   
34 #leftnav {
35     float: left;
36     width:150px;
37     padding: 5px;
38     margin:0;
39   
40 }
41 #rightnav {
42     width: 150px;
43     float:right;
44     padding: 5px;
45     margin:0;
46   
47 }
48 #content
49 {
50     margin: 0 180px 0 180px;
51     padding: 1em;
52     border-left: 1px solid gray;
53     border-right: 1px solid gray;
54     font-family"Times New Roman",sans-serif ,arial, helvetica;
55     font-size: 1.0em;
56     line-height: 1.6em;
57   
58 }
59 #footer {
60     clear:both;
61     padding: 0 3px;
62     border-top: 1px solid gray;
63   
64 }

Download source code:3colcsstut.zip

Introduction to CSS

Jun 22

Introduction to CSS


HTML was originally designed as a simple way of presenting information, with the aesthetics of a web page being far less important than the content (and largely being left up to the web browser). Of course, now that the web has become as popular as it has, the presentation of your content has become almost critical to a site鈥檚 success. CSS is the key presentational technology that is used to design websites.

This page was last updated on 2010-01-08

searchHiOption();

What are Stylesheets?

In the late 鈥90s, HTML coders noticed that they were retyping the same old tags again and again on the same page, leading to bigger HTML files and above all, time consumption and frustration. You may have found yourself in the same situation, adding in mountains of <font> tags, despite wanting them all the same; or using tricks like invisible gifs for spacing.

Then, someone had a great idea: have one file that defines all the values that those piles of tags would have done, and then have all your pages checking this file and formatting your pages accordingly. You can therefore leave out most of the formatting tags in HTML and use only nice structural elements (like headings, paragraphs and links) — separating structure and presentation.

In late 1996 CSS (Cascading StyleSheets) became a reality, forged by our good friends the » World Wide Web Consortium (W3C). Your stylesheet acts as a partner to your HTML code; taking care of all the layout, fonts, colours and overall look of your site.

If you ever decide to change the look of your site, you modify that one CSS file (your style sheet) and all the HTML pages reading from that file will display differently. This makes maintenance of your design much easier.

Benefits of CSS

Another of CSS鈥檚 boons is that you define things once, making it far more efficient than defining everything in HTML on every page. This means:

  • Pages download faster, sometimes by as much as 50%
  • You have to type less code, and your pages are shorter and neater.
  • The look of your site is kept consistent throughout all the pages that work off the same stylesheet.
  • Updating your design and general site maintenance are made much easier, and errors caused by editing multiple HTML pages occur far less often.

Well-authored CSS also improves the accessibility of web content, allowing access through myriad devices (handheld PDAs for example) and ensuring that web users with disabilities are still able to receive it. It also eliminates the need for browser-specific hacks and tags, which means your site has a better chance of working across all major browsers.

Initially vaguely intimidating, CSS is a well-designed, elegant language. It is hugely important for the future of web design, and has been pivotal in helping designers move away from the problematic, hack-ridden days of presentational HTML tags like <font>, and allowed us to return to using logical, structural elements which make our sites more accessible.

All that, and there are dozens of powerful extra formatting options and possibilities available through stylesheet commands that are not possible through normal HTML. You鈥檒l see these later on when we get on to things like backgrounds, spacing, layers and borders.

Browser Compatibility Note:

The W3C have thus far released two major versions of the CSS specifications: » CSS 1 and » CSS 2, in 鈥96 and 鈥98 respectively. These standards work the same as new HTML standards do, with new features added in each subsequent version. CSS 3 is currently under development but won鈥檛 be finalised for a few more years.

Browsers began to support stylesheets properly at the version 4 mark. Internet Explorer 3 had some basic understanding, and Netscape Navigator 4.7 was very glitchy. By version 5 of » Internet Explorer the browser was coming close to full compatibility of the first of these two standards, though many bugs in its implementation remained.

CSS 2 and beyond are now close to being supported properly in full, particularly in the more sophisticated browsers like » Firefox, » Chrome, » Opera and » Safari. It took many painful years, but everybody should be using CSS today.

Implementation

CSS files are termed 鈥渃ascading鈥 stylesheets because of two reasons: one stylesheet can cascade, or have influence over, multiple pages. Similarly, many CSS files can define a single page.

There are 3 ways to implement css commands into your site:

  • Use one CSS file for all your pages. This is the best way to do it.
  • Integrate CSS commands into the head of each of your documents.
  • Use the style attribute to put CSS code directly into a HTML element.

CSS allows you to use all three of these methods in glorious tandem, inheriting and overriding values as you go (we鈥檒l get on to all that in the next tutorial).

One Central Stylesheet

This is how you should use most of your CSS. You write just one .css file and have all your pages referencing it. This way, a change to anything in this one file will adjust this thing (a font, for example) across your whole site. You could change your entire colour scheme with one modification if you want, over an unlimited number of pages. That鈥檚 one of the things CSS was designed for — flexibility.

To create your stylesheet, open a text editor (NotePad or SimpleText will be fine). Remember in the very first lesson on this site, you learned how to save from a text editor into the .html file format? Well, here you鈥檒l be doing roughly the same except your file will have a .css suffix. Just save a blank file as mystyles.css and put it in the same directory as your homepage. Now that you have that, I can show you the syntax used in CSS:

Very Importantselector {property: value; property: value; property: value; }

And now a worked example:

p {color: blue; font-size: 120%; }

Just put that one line into your file for the duration of this tutorial. That鈥檚 all you need. This rule applies to all paragraph elements. Once you鈥檝e linked the stylesheet to your pages, having this style declaration in your css file would make all the text in your pages enclosed in the <p> and </p> tags blue, and sized 120% as big as the default font size.

This is how all the affected paragraphs will be formatted.

Have a look over these rules:

  • The selector is usually the name of a tag, without its surrounding angle-brackets.
  • The braces are {curly}, not [square] or (round).
  • After the property name there is a colon, and between each individual part there is a semicolon. Each of these pairs of properties and values is a declaration.

You could add another line in under your first one. Try this line of CSS and then use some large headings on your page:

h1 {font-family: Verdana, sans-serif; color: red; font-size: 20px; }

Your stylesheet should look something like this. If you want to affect multiple selectors with the same CSS formatting, add them all together, with commas:

p, div, h1 {color: #00DDFF; width: 80%; } /* modifies all 3 tags */

As above, you can also add comments to your stylesheet using the /*...*/ delimiters. These can give you or anyone else using your stylesheet vital tips about what鈥檚 going on in your code.

Attaching Your Stylesheet

Now that you have something in your file, you鈥檒l need to show your pages where their css file is. Put this line of code into the head part of any documents you want to read this file:

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

This could be a new tag to you — rel stands for the file鈥檚 鈥楻ELationship鈥, and type shows that it鈥檚 a text file acting as a CSS stylesheet. Once you鈥檝e made sure that the href is correct (it can be defined absolutely or relatively), you should see your pages being formatted with your preferred values. You can link multiple stylesheets to each page if you want, like having one file with all your fonts, another for margins and spacing etc.

Individual Style blocks

If you use a common design across all of your site鈥檚 pages, you should be using the method above. If, however, a number of pages need some particular styling and you need to override the values you鈥檝e defined in your main stylesheet, you can use the style blocks method. To embed style, put this into your head:

<style type="text/css">

p {font-weight: normal; color: gray; }

h1 {color: black; }
</style>

The type attribute here allows browsers to treat this code as CSS. CSS code applied in this way is not technically a stylesheet , but is called an 鈥渋nline style block.鈥

Using the Style Attribute

If you need to modify one tag on its own you can embed style information into it using the style attribute:

<p style="color: blue; font-family: Arial; ">

The style formatting will stop as soon as you close the tag it鈥檚 applied to, just like any other attribute, so it will be just this paragraph that will be affected. Also note that there aren鈥檛 any curly braces used here, but the colon/semicolon rule still applies.

This method is useful for once-off formatting, and overriding previously defined properties, but you shouldn鈥檛 use it very much. If you find yourself adding the same style to multiple tags, it might be worth your while promoting it to your main stylesheet, to save time and space.

If you鈥檇 like to see a fully-functioning stylesheet, you can look at ours: bubbleicious.css (use Notepad to open). Don鈥檛 be overwhelmed by the complexity, as there are some more advanced techniques being used that haven鈥檛 been explained yet...

So, that was your introduction. Now, gain some crucial control over your CSS with some slightly more advanced techniques...

Advanced CSS

Jun 22

Advanced CSS


First off, you're going to need a thorough grasp of the basics of CSS before you go into this. It's been easy so far, and this trend will continue here.

CSS is a simple language with a lot of depth. There are many techniques you can use to get more out of your stylesheets. There's another implementation you've yet to learn; with classes and ids you will be able to set up custom ways of styling elements without having to change the fundamental properties of a HTML tag; and contextual style gives you yet another level of control.

This page was last updated on 2010-01-08

searchHiOption();

The search terms you used to find this page can be highlighted. Click the button to toggle this feature on or off.



Importing Stylesheets

There is a fourth method of applying a stylesheet to your pages, suitable for CSS that you don't want old browsers trying to use. It is similar to the <link> method discussed in the introduction, but is only supported by browsers of versions 5 and above. Netscape and Internet Explorer 4 will not be able to read the stylesheet you supply this way, and so it is useful to apply things like positioning and CSS layout through this method, as old browsers mangle this code and occasionally crash if you give it to them. The code to import, which is placed in the <head>, is:

<style type="text/css" media="all">
@import "style.css";
@import "advanced.css";
</style>

It should be noted that this method is not available specifically to block out stylesheets to old browsers. It just happens that the two version 4 browsers did not support this implementation. This method is meant as a way to add partial stylesheets to your main sheets, so many sources are combined as one.

Implementation Overriding

CSS code can override other existing CSS code depending on how it is implemented. Say you had redefined the p tag in an external stylesheet. If you redefine it again in the head section of a document, this definition will be the one that is used, as it is closer to the things that it affects. Adding css using the style attribute will override anything else that has been specified elsewhere.

Overriding-wise, the sheet imported last will override the imported ones that come before — i.e. in the example above, 'advanced.css' has more weight than 'style.css' because it is imported below it. Imported stylesheets have the least influence over the final presentation of a page overall, as linked sheets will override them. So we finally have a full cascade order:

  • the style attribute overrides
  • a style block, which overrides
  • a linked stylesheet, which overrides
  • an imported sheet.

classes and ids

If you have been using a stylesheet to reformat HTML tags you will probably have wished you could just set up certain ways of formatting HTML elements and apply them to multiple tags. Without these two methods of CSS implementation, you'd soon run out of tags to reformat.

Using classes and ids (which are roughly the same thing), you can set up these custom options, which allow you to format single tags in many different ways. They're easy to set up, fast and flexible.

classes

Class selectors are created by typing a dot followed by the class name. Before you start putting in these, you should have an existing stylesheet or style block to add them to. That was all covered in the intro to CSS. Now, say you wanted to format lots of individual pieces of text as 12 point red Verdana. Adding the font face, color and size HTML around every instance where you want this type of text is a load of code, and a whole load of coding. This is the beauty of classes. Put this line of CSS into your style:

.caution {font-family: Verdana; font-size: 12pt; color: red; }

Note the dot before the name you want to use for it. You've just set up a class. Now, you can add class="caution" to any element and it will be formatted as such. Try it out on a couple of tags, like <p class="caution"> and <h1 class="caution">. When you're giving the name of the class here, the dot does not appear. Try to name the classes based on their function rather than their presentation.

ids

ids are practically the same as classes, with one difference. Only one element can be given each id per page. They can be used for elements you know will only occur once, such as header and navigation tables. If you want to use them, the code is the same, but with hashes (#) in place of the dots.

#header {width: 90%; background: white; font-size: 20px; color: purple; }

<div id="header">stuff</div>

ids are also in place to take over from the name attribute as the tag that creates internal links, but this has yet to become fully supported. More often than not, id values are used in JavaScript for referencing page elements, and are necessary for DHTML.

Both class and id names can contain characters a-z, A-Z, digits 0-9, underscores and hyphens, but they cannot start with a number or dash.

<span>

Now, I'll introduce the span tag. It does exactly what you'd expect — it influences any other code that it spans. So, to use it in conjunction with the class you set up above, do this:

<span class="caution">affected text</span>

This would create your desired text, without a font tag in sight. Note that the span tag does absolutely nothing on its own without the class attribute.

The best part about class implementation is that it isn't confined to any one tag. You use span when there isn't any other tag around the text you want to affect. But; if the text is also being bolded, you can just add the class attribute to that instead, which means the text takes on the effects of the tag and the css in the class.

<b class="caution">text</b> will create text

If you wanted all your instances of the class to be bold, you modify the class code — and every occurrence of it on your site changes instantly. But if you only want one instance to be bold, you just add the class to the bold tag that's around that specific text. This saves you having to set up a whole new class when it would be inefficient to do so.

Overriding

If you wanted one of the instances of caution to be the same as the rest, but green instead of red, instead of setting up a whole new class with just this changed, you can override this aspect of the css by putting further style definitions closer to the affected text than the class that defines it. We'll call this 'overriding by proximity', because that sounds cool. For example:

<span class="caution" style="color: green">text</span>

Here I've embedded style into the tag, the most powerful overriding technique. If the caution class was specified in an external stylesheet I could have added the modification into a style block and it still would have overridden the class, due to the cascading order defined earlier on in this tutorial. In any case, the text will be displayed in 12pt green Verdana. If you want text vastly different, set up further classes. You can have an unlimited number, so long as they all have different names.

Contextual Style

Contextual style is a powerful technique that can save you from having to define too many classes. You can have your stylesheet apply CSS rules to an element, depending on what other elements it is contained in. For instance, if I wanted all strong elements that are contained in paragraphs to be red, I could write

p strong {color: red; }

You just list the selectors (which can be element names, classes or ids) in descending order, with single spaces between them. Using this method properly is a real time-saver.

sourcetip: All of you out there using XHTML should use lowercase selectors in your code, to match the all lowercase elements in your source code.
A rule like STRONG {color: red; } might not be applied, while strong {color:red; } is safe.

For a further example, you could get all the links that occur in your navigation bar (which you've defined as div id="navigation") to be white with

div#navigation a {color: white; }

This spares you from having to add class="nav", or whatever, to all of those links. Above I'm illustrating another technique you can use. If you define your navigational area using the selector div#navigation instead of just #navigation your stylesheet will be easier to read without you having to add in comments.

Totally Pwn CSS with Javascript

Jun 22

Filed: Fri, Feb 16 2007 under Programming|| Tags: .css1 javascript css dynamic

The last great frontier for a Javascript programmer is usually the direct manipulation of a stylesheet. While incredibly powerful tools, the documentation is sparse and the browsers rife with incompatibilities. You may be sending floating divisions flying across the screen playing videos of spanking kitties, but have you ever created a new stylesheet class on the fly? No? Read on!

Tools for the Toolbox

We'll dive right in with three functions which will make working with stylesheets very trivial. After the functions are documented there will be a short tutorial and reference for those who want to go beyond the basic tools.

function getCSSRule(ruleName, deleteFlag) {               // Return requested style obejct
   ruleName
=ruleName.toLowerCase();                       // Convert test string to lower case.
   
if (document.styleSheets) {                            // If browser can play with stylesheets
     
for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         
var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         
var ii=0;                                        // Initialize subCounter.
         
var cssRule=false;                               // Initialize cssRule.
         
do {                                             // For each rule in stylesheet
           
if (styleSheet.cssRules) {                    // Browser uses cssRules?
               cssRule
= styleSheet.cssRules[ii];         // Yes --Mozilla Style
           
} else {                                      // Browser usses rules?
               cssRule
= styleSheet.rules[ii];            // Yes IE style.
           
}                                             // End IE check.
           
if (cssRule)  {                               // If we found a rule...
               
if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                 
if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     
if (styleSheet.cssRules) {           // Yes, deleting...
                        styleSheet
.deleteRule(ii);        // Delete rule, Moz Style
                     
} else {                             // Still deleting.
                        styleSheet
.removeRule(ii);        // Delete rule IE style.
                     
}                                    // End IE check.
                     
return true;                         // return true, class deleted.
                 
} else {                                // found and not deleting.
                     
return cssRule;                      // return the style object.
                 
}                                       // End delete Check
               
}                                          // End found rule name
           
}                                             // end found cssRule
            ii
++;                                         // Increment sub-counter
         
} while (cssRule)                                // end While loop
     
}                                                   // end For loop
   
}                                                      // end styleSheet ability check
   
return false;                                          // we found NOTHING!
}                                                         // end getCSSRule

function killCSSRule(ruleName) {                          // Delete a CSS rule  
   
return getCSSRule(ruleName,'delete');                  // just call getCSSRule w/delete flag.
}                                                         // end killCSSRule

function addCSSRule(ruleName) {                           // Create a new css rule
   
if (document.styleSheets) {                            // Can browser do styleSheets?
     
if (!getCSSRule(ruleName)) {                        // if rule doesn't exist...
         
if (document.styleSheets[0].addRule) {           // Browser is IE?
            document
.styleSheets[0].addRule(ruleName, null,0);      // Yes, add IE style
         
} else {                                         // Browser is IE?
            document
.styleSheets[0].insertRule(ruleName+' { }', 0); // Yes, add Moz style.
         
}                                                // End browser check
     
}                                                   // End already exist check.
   
}                                                      // End browser ability check.
   
return getCSSRule(ruleName);                           // return rule we just created.
}

getCSSRule -- Return a CSS rule

These are three simple and easy to use functions. getCSSRule(ruleName) will accept a CSS selector (classname, divname, etc) and if it exists will pass back the style object. Lets say you have a class called .global. To retrieve this style all you have to do is the following...

var global = getCSSRule('.global');

Global is now a pointer to the stylesheet rule for the class global and you can now manipulate it pretty much exactly like you would manipulate any getElementById object! For instance to give the class an overline and underline property just issue the following command鈥

global.style.textDecoration='underline overline';

This works for any defined selector. For instance if you have an ID match #global then you would retreive it via鈥

var global = getCSSRule('#global');

And of course it works on raw HTML elements. For instance to get your style for all the paragraph tags鈥

var global = getCSSRule('P');

getCSSRule goes by exact match. So if you have a rule for .global DIV you will need to specify .global DIV to get that rule, just .global won't cut it. If getCSSRule can't find the selector you're looking for it will return FALSE.

killCSSRule -- Delete a CSS rule

This is a VERY simple function. All it does is call getCSSRule with your ruleName and a delete flag. When getCSSRule finds your rule it will delete it and any objects on the page with that style will instantly become unstyled. Again this is an exact match function.

addCSSRule -- Create a new CSS rule

This is a really cool function. It basically accepts a rule name, creates an empty ruleset in the first stylesheet, and then returns the stylesheet object it created. Why is it cool? Well if you pass it a string p then you can instantly style every paragraph on the page. If you're creating a javascript distribution you don't have to distribute a css file with your javascript source, you can just create the stylesheet rules automatically with this function. Passing it .globalTwo would create a new classname called globalTwo and passing it #someDiv would let you style some division with an ID of someDiv. Here's an example:

var global2 = addCSSRule('.global2');
    global2
.style.backgroundColor='green';
var someDiv = addCSSRule('#someDiv');
    someDiv
.style.fontWeight='bold';

The caveat is that this works with the first stylesheet on the page regardless of the media type. So make sure your screen CSS appears as the first stylesheet if you want to use addCSSRule, otherwise -- while it may appear your new styles are going into a black-hole, your printouts may end up looking VERY funky indeed!

Creating a StyleSheet Dynamically

If you have the need, you can create a stylesheet dynamically, on the fly, through javascript with the following code...

var cssNode = document.createElement('style');
cssNode
.type = 'text/css';
cssNode
.rel = 'stylesheet';
cssNode
.media = 'screen';
cssNode
.title = 'dynamicSheet';
document
.getElementsByTagName("head")[0].appendChild(cssNode);

This will create a new style tag, assign it its attributes and then append the new object to the head tag of the current page. Since we assigned a title we can find our new sheet just by checking the title as we loop through the stylesheets.

Loading a StyleSheet Dynamically

You can load an external stylesheet dynamically with the following code.

var cssNode = document.createElement('link');
cssNode
.type = 'text/css';
cssNode
.rel = 'stylesheet';
cssNode
.href = 'http://www.somedomain.com/styles/FireFox.css';
cssNode
.media = 'screen';
cssNode
.title = 'dynamicLoadedSheet';
document
.getElementsByTagName("head")[0].appendChild(cssNode);

This is much the same as our previous example but here the element we create is a 'link' and we specify an additional href attribute which gives the url of the external stylesheet. The moment the new node is appended to the "head" of the html page, the stylesheet is loaded and applied.

Go forth in Style!

And there you have it, a few simple routines that let you totally pwn stylesheets in Javascript. There's room for improvement of course. getCSSRule can be modified to do substring matching and return an array of items, and addCSSRule can be modified to look for the media type of the stylesheet and even add a stylesheet if it has to.

If you're curious about how Stylesheets are stored and accessed in the Document Object Model, then read on!

document.stylesheets[]

Your stylesheets are stored in the document.styleSheets property. This is an array with each element of the array being one of the stylesheets associated with this page. document.styleSheets[0] would give you the first stylesheet on the page. Simple code which just flips through a pages styleSheets would look like this...

for (var i=0; i<document.styleSheets.length; i++) {}

The stylesheets have the following objects and properties:

Methods
addRule(selector, rules, [index]) IE Adds a rule. By default rules are added to the end of the stylesheet but you can specify an index (starting at zero).

document.styleSheets[0].addRule(".demoClass", "background-color: blue")

insertRule(rule, index) FireFox This is the same as IE save the rule is bundle in one string. .demoClass {background-color: blue}.
removeRule([index]) IE This will remove the first rule of the stylesheet if no index is specified or the rule at the index position.
deleteRule(index) FireFox This is the same as IE, it will remove the rule at the index position.

Properties
cssRules[] FireFox An array containing the rules for the current styleSheet
rules[] IE An array containing the rules for the current styleSheet
disabled all True if this stylesheet is disabled, false if its active.
href all The source URL of this stylesheet, if any.
imports[] IE An array of all the @import(ed) rules.
length all The number of stylesheets in the array
media all The media this stylesheet is active for (not always screen!)
ownerNode FireFox returns the DOM parent of this object, usually link or style.
owningElement IE returns the DOM parent of this object, usually link or style.
ownerRule FireFox If this sheet is a child via @import, this points to the parent.
parentStyleSheet all If this sheet is the product of a @page or @import, this property references the parent stylesheet.
title all If the style or link tag defined a title attribute, here it is.
type all If the style or link tag defined a type (text/css), here it is.

document.stylesheets[x].cssRules[]

Once you have a styleSheet selected, you can access the individual rules via the rules[] array for Internet Explorer or the cssRules[] array for Mozilla. For instance if you have a stylesheet defined as such鈥

<style>
   
.global { background-color: white }
</style>

鈥hen to reference .global you'd use the following...

   document.styleSheets[0].cssRules[0];

That would give you the first rule of the first stylesheet, which in this case happens to be .global. cssRules[] and rules[] have the following properties.

Properties
cssText FireFox Returns the styles of the present rule -- {float: left; text-align: right}
length all Returns the number of rules in this stylesheet
parentStyleSheet all Pointer to the styleSheet which contains these rules
selectorText all this is the name of the rule. For instance using our example above: .global
style all This is a style object that you can manipulate just like document.getElementById('someDiv').style

The really important items here are .length (which lets you know how many times you're going to have to loop to check each cssRule[], selectorText which lets you look for a specific classname (or other selector) like .global and style which lets you manipulate the rule just like any other javascript .style.rule='value' object.

Going back to our global example again. If we wanted to change its rule to be bold text then it's as simple as doing this...

document.styleSheets[0].cssRules[0].style.fontWeight='bold';

There are other methods and properties. For a seriously excellent overview of document.spreadheets[] I highly recommend you visit howtocreate.co.uk and scroll down to document.spreadsheets[]. You can click on a method or property for more information.

Bringing it all together

Now that you know the methods and properties of the styleSheets[] and cssRules[] arrays it's pretty easy to see that our getCSSRule(ruleName) function just loops through each of the styleSheets and then through each cssRule[] in those sheets until it matches

document.styleSheets[x].cssRules[x].selectorText==ruleName

Once we have a match then we just return document.styleSheets[x].cssRules[x] which is a css object we can manipulate through the .style property just like any other div.

Exploit the Rules!

Manipulating a HTML object's styles is powerful, but going beyond the one object and manipulating the stylesheets directly is even more powerful. With this you can instantly disable every input field of a form, or reactivate them. Hide every link, or make them re-appear -- in a size 72 font. Ok maybe that's not practical, but it sure sounds fun!

More importantly, the information in this article allows for javascript modules to be fully self-contained, needing nothing more from the end user than dropping in an include file. Once the script is loaded it can create all the divisions it needs to store the data and create all the styles and classes it needs to function.

It's one of those things where the more you use it, the more indespensible it becomes.

Happy Coding!

Replacing table layout with CSS

Jun 22

I am a great believer in learning from example. I've written a simple CSS style sheet that can be used in two or three column layouts with a header and footer. You are welcome to use that to layout your web site, or just play around with it to learn CSS.

Download the layout.css style sheet and save it in the same directory as your html files.

Linking to an external CSS file

We've written a standard html document and included the layout.css file from a line of code in the <head>. We'll keep adding to the html on this page, and will highlight new code in blue.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>CSS Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

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

</head>

<body>

</body>
</html>

Laying out columns

There are two ways to lay out columns in CSS: Absolute positioning and Relative positioning. Both methods are very flexible, but unfortunately Dreamweaver MX and some browsers get very confused by relative positioning so I'll only consider absolute positioning in this document.

Using the <div> tag

Let's go straight into the layout for this page. It was created using <div> tags. <div> a way of separating data in an html page.

Let's make a page using three divs. It's a standard html page that you can use with our layout.css file. We've highlighted the new bits of code in blue.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>CSS Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="layout.css" rel="stylesheet" type="text/css">
</head>

<body>

<div id="header">Header - My title will go up here.</div>

<div id="centreposition">Centreposition - This is the centre of the page.</div>

<div id="footer">Footer - This is the footer.</div>

</body>
</html>

Notice we are calling the style from the style sheet using an "ID=". This works a lot better for layout than the alternative "class=" method. We have set background color in the style sheet so the divs look different:

Header - My title will go up here.

Centreposition - This is the centre of the page.

Footer - This is the footer.

Each div starts on a new line. That's going to come in handy, but there isn't a navigation column on the page yet. Let's make room for one.

Using Padding

We've set a value for padding on the centre div in the CSS file. The html code still looks the same, we've just altered the CSS file so that anything inside the centreposition div is indented 20% into the page. This makes room for the navigation column.

Header - My title will go up here.

 

Centreposition - This is the centre of the page.

Footer - This is the footer.

Inserting navigation

The navigation can then be inserted as an absolutely positioned <div> in the space we created:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>CSS Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="layout.css" rel="stylesheet" type="text/css">
</head>

<body>

<div id="header">Header - My title will go up here.</div>

<div id="centreposition">Centreposition - This is the centre of the page.</div>

<div id="footer">Footer - This is the footer.</div>

<div id="left">Left - for the navigation<div>

</body>
</html>

We've just added an extra div beneath the other divs. We can place the navigation anywhere within the code of the html page, and it will always appear in the right place. That's because we've used absolute positioning in the CSS file.

Header - My title will go up here.

This is the left navigation

Centreposition - This is the centre of the page.

Footer - This is the footer.

OK that's great too, but the background to the left navigation only goes halfway down the page, then the colour is the same of the centreposition div. The way around this is to put another div inside the centreposition div.

Putting a div inside a div

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>CSS Layout</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="layout.css" rel="stylesheet" type="text/css">
</head>

<body>

<div id="header">Header - My title will go up here.</div>

<div id="centreposition">

<div id="centrecontent">

Centrecontent - This is the new centre of the page.

</div>

</div>

<div id="footer">Footer - This is the footer.</div>

<div id="left">Left - for the navigation<div>

</body>
</html>

Header - My title will go up here.

Left - for the navigation

Centrecontent - This is the new centre of the page.

Footer - This is the footer.

The position of the new centrecontent div is inherited from the centreposition div, but we've specified a new values for border and background in the new div.

Finishing off

All that remains is to set the left navigation background as transparent so it will inherit the background color from the layer beneath it.

Header - My title will go up here.

Left - for the navigation

Centrecontent - This is the new centre of the page.

Footer - This is the footer.

The three column layout

To add a column on the right, all we need to do is add padding to the right in the centreposition style in the CSS style sheet, then add another absolutely positioned <div> like we did for the navigation on the left.

How we've used CSS

Our header div is blank. All of the information in our header is in the form of additional absolutely positioned divs. The header div is only there to force the main part of the page downwards by 100 pixels.

We've added a column on the right, all we needed to do was add padding to the right in the "#centreposition" style in the CSS style sheet, then add another absolutely positioned div like we did for the navigation on the left.

Find out more

The W3C are the guys that defined CSS in the first place. The W3C CSS home page contains a great deal of useful reference material.

The W3C site also contains full specifications for CSS2

48: Dynamic style - manipulating CSS with JavaScript

Jun 22

48: Dynamic style - manipulating CSS with JavaScript

By Greg Schechter 路 3 Feb, 2009

Published in: , , , ,

Introduction

At this point in the JavaScript section of the course, you鈥檝e already covered the real basics of JavaScript usage, looked at how to target elements using the DOM, and seen how to manipulate them once you鈥檝e successfully targeted them.

In this article we will look at how to dynamically update the styling applied to your elements by manipulating your CSS at runtime using JavaScript. It uses the same kind of technique that we鈥檝e already seen, but there are a few special considerations to keep in mind when working with the CSS DOM. We鈥檒l cover these in the following sections:

Accessing style sheets

The browser provides an interface to interact with style sheets — in your JavaScript code you can access a list of your style sheets by using document.styleSheets. document.styleSheets will return a list of all of the style sheets applied to a page, including external style sheets referenced with a link element and internal style sheets residing inside style elements. If your style elements have id attributes, you can reference them quickly with document.getElementById(element_id).

You can also add new style sheets to the page — you can use the document.createElement function to create a new style element. This is useful when you want to give site visitors the option of changing your site styles dynamically, using some button controls perhaps. Here is a quick example of how you could create a new style sheet:

var sheet = document.createElement('style')
sheet.innerHTML = "div {border: 2px solid black; background-color: blue;}";
document.body.appendChild(sheet);

Removing a style sheet is also very simple. First you must obtain the style sheet you wish to remove. You can do this by using document.getElementById, as shown in the small example below. To remove a style sheet you can use the DOM function parent.removeChild(element), where element is the style sheet object you wish to remove and parent is the parent node of our style sheet. As shown in the example below, to remove the style sheet (sheetToBeRemoved) you first get the style sheet's parent — var sheetParent = sheetToBeRemoved.parentNode — then you call removeChild with an argument of sheetToBeRemoved - sheetParent.removeChild(sheetToBeRemoved)

var sheetToBeRemoved = document.getElementById('styleSheetId');
var sheetParent = sheetToBeRemoved.parentNode;
sheetParent.removeChild(sheetToBeRemoved);

The accessing style sheets example demonstrates both accessing all styles sheets and adding and removing a new style sheet to the page.

Style Sheet Properties

The stylesheet object is available through JavaScript, and allows you to access information about a style sheet referenced from the current web page, such as if it is disabled, its location, and the list of CSS rules it contains. For a full list of the properties of the stylesheet object (and many things besides), check out the W3C Document Object Model Style Sheets documentation.

Let鈥檚 consider a (currently) theoretical example — say we have a website where we show a series of technical articles. We want to spotlight some of these articles in a nice animated carousel, but what about users that don鈥檛 have JavaScript enabled for whatever reason? Thinking back to our unobtrusive JavaScript knowledge, we want the website functionality to still work for these users, but we might want to style the site differently for those users so that their user experience is still pleasant, even without the carousel.

What you want is a style sheet that gets enabled only if JavaScript is enabled. You are in luck — the DOM style sheet interface gives us access to the disabled attribute, which allows us to turn style sheets on or off.

Most of the properties of the stylesheet object are read only, but some, such as disabled, aren鈥檛.

You can also use the style sheet properties to help differentiate between multiple style sheets on the page. The src property can help you identify external style sheets, but it won鈥檛 help you to reference internal style elements. A better way, which allows you to reference both internal and external style sheets individually, is to use the title property. If you iterate through document.styleSheets you can differentiate between the different style sheets you have included on the page. The following example shows how you can accomplish this iteration:

function getStyleSheet(unique_title) {
  for(var i=0; i<document.styleSheets.length; i++) {
    var sheet = document.styleSheets[i];
    if(sheet.title == unique_title) {
      return sheet;
    }
  }
}

For each stylesheet object retrieved from the styleSheets array you can access its title property to check if it has the title our code is looking for. You can see a functional example of this in the adding and removing rules example, which I will discuss in the next section.

Switching between different style sheets based on user preference is a fairly common web site feature — using what we have discussed so far, you can set up multiple style sheets and enable only the ones that the current site visitor would want to view. Let鈥檚 look at a real example — initially the text is styled, but when we set the disabled attribute to true, our defined CSS gets disabled. You can easily turn the CSS back on by setting disabled to false. Check out my style sheet properties example for a practical look at how to use this.

Adding and Removing Rules

Remember the theoretical showcase site we discussed above? Let鈥檚 say this site has a list of articles; some are about CSS, some are about HTML, and some are about JavaScript. On our webpage we show all the articles at once, but our user only wants to see the CSS articles. How might we do this? Because all the articles are already being shown, we don鈥檛 want to do another round trip to the server to get to a page containing just the CSS articles — that is a waste of time.

To solve this issue, we can use JavaScript to either iterate through all the articles and only make the CSS articles visible (I鈥檒l discuss how to do this later), or add a rule to one of our style sheets that will make only the CSS articles visible. Using CSS will actually be faster than traversing over all the elements.

Our stylesheet object has two functions to help us with this problem. First is the insertRule function, which looks like this:

stylesheet.insertRule(rule,index)

rule is a string containing the rule we would like to add to the style sheet. index specifies where within the style sheet鈥檚 rule list the rule should be placed. Here is how it might look.

stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

I鈥檝e created an example to demonstrate how the insertRule function is used. In this example is a list of all the rules in a style sheet. When the button is pressed it adds a rule with an index of 2 to make the text red by adding the property color: red to the p { ... } rule. Take a look at the adding and removing rules example.

If you want to delete this rule, you can call the function stylesheet.deleteRule(index), where index is the index of the rule you want to be removed.

In our article showcase example, we can create a rule that turns the display to none for all the HTML and JavaScript articles — check out the carousel example to see this in action.

Note: IE does not implement rules according to the standard. Instead of the attribute cssRules it uses rules. IE also uses removeRule instead of deleteRule and addRule(selector, rule, index) instead of insertRule.

Changing Element Styles

At this point you should understand how to edit style sheets connected to the page and create and modify the CSS rules within them. What if you want to change a specific element inside the DOM? Using the DOM API you can access the specific elements of your page. Looking back at our carousel example, functionality is defined so that when you click on an article, that article becomes highlighted while the main article text gets displayed below.

Through the DOM, you have access to a style object that describes the style of an element. This style object is defined as a CSSStyleDeclaration; you can see a detailed explanation of this at the W3C documentation of the CSSStyleDeclaration interface. The style object doesn鈥檛 quite work the same as some of the other properties defined in your HTML element. Unlike element.href or element.id, which return strings, element.style returns an object. This means you cannot set the style by assigning a string to element.style.

The style object has attributes that correspond to the different CSS properties we set. For example, style.color returns the colour that element has set on it. By calling element.style.color = "red"; you can apply the style change dynamically. Below is a function that turns an element鈥檚 colour to red when you pass it the element鈥檚 id.

function colorElementRed(id) {
  var el = document.getElementById(id);
  el.style.color = "red";
}

You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.setAttribute('style', 'color: red'); on the element, but be wary as this will erase any changes you have made to the style object.

When you set the style of an element in this manner it is the same as if you were assigning it as a declaration in a style attribute of the html element. The style will only be applied if the importance and specificity of the rule is greater than the other rules applied to the element (specificity is explained in the article about the inheritance and cascade of CSS.

Some of you may be wondering what happens when the CSS property being set has a hyphen. The syntax has to be different here, because for example if you write element.style.font-size, JavaScript will try to subtract size from the element.style.font notation, which is not what you want to happen. To stop this problem from occurring, all the CSS properties are written out in CamelCase. As shown below, you should write element.style.fontSize to access the element鈥檚 font size. For example:

function changeElement(id) {
  var el = document.getElementById(id);
  el.style.color = "red";
  el.style.fontSize = "15px";
  el.style.backgroundColor = "#FFFFFF";
}

Remember those stylesheet objects? Well, styleSheet.cssRules will return a list of style objects representing all the CSS rules contained in the style sheet. You can use these style objects just like the style objects for the other elements. In this case, rather than changing one specific element on our page, changes here will change all elements that the CSS rules apply to.

In the example below, the function to make the text bigger uses the style object and the function to make it smaller uses setAttribute. If you set the text to red and then call setAttribute with the smaller text button, you will notice that our change gets overwritten. Check out the changing element styles example live.

Element Class Names

Another way to alter the style of an element is by changing its class attribute. class is a reserved word in JavaScript, so in order to access the element鈥檚 class, you use element.className. You can append strings to className if you want to add a class to an element, or you could just overwrite className and assign it a whole new class. Check out the element class names example.

Summary

Knowing how to dynamically change the styles applied to your page is extremely useful for building modern, rich interactive web pages — the knowledge presented in this article forms the basis of more advanced techniques such as JavaScript animations. You just need to take care to use your style modifications responsibly, and not use them excessively. As we also discussed above, style modifications can also improve the efficiency of web experiences — showing and hiding content can help to avoid needless trips to the server in certain circumstances.

Exercise Questions

  • What is the difference between setAttribute and setting the style through the CSSStyleDeclaration object?
  • List two ways that you could cause all images to have a green border when a user clicks a button.
  • Will changing the CSSStyleDeclaration object of an element always change the element鈥檚 style? Why?
  • List two ways to access a specific style sheet.

About the Author

Greg Schechter is very new to the web technology industry — he is currently studying computer science at the University of Illinois in Urbana Champaign. He is very eager to enter the web applications industry where he hopes to build rich and useful web sites for the users of the world. One can find more details about Greg at GregTheBusker.com.

鞓ろ攬 靻岇姢 鞗 霐旍瀽鞚 OSWD.ORG

Jun 22

http://oswd.org