Neticulis.com > Programming > Learning CSS

└>Lesson 3: CSS Selectors Tutorial

Basic HTML->CSS Selectors
Basic CSS Selectors include most HTML tags, the <a> tag for example is used for links in html, and can reference any css selectors named "a". <div> references css named "div", and so on. So if you wanted to change every link on your page to be a certain color, you would simple write this in css:

a {
color: #FF0000;
}


And let us take <img> for example, we will add a 5 pixel red border, which will be applied to all html <img> tags:

img {
border-width: 5px;
border-color: red;
}

Using the class selector
Many times you will find that you need multiple rules for the same tag, for example if you wanted two links to be presented differently, one red and the other blue, in this case you would use the class selector. You simply define a name for you class and append it to the original selector with a period, here is the example:
I am a red link!
I am a blue link!

The CSS:
a.redlink { color: red; }
a.bluelink {color: blue; }


Now all you have to do is define which class you want your link to use, like so:
<a href="http://www.google.com" class="redlink">I am a red link!</a>
<a href="http://www.google.com" class="bluelink">I am a blue link!</a>


Be aware that you can use the class selector on its own, without the original selector prepended, just make sure to keep the period in front of the class name:
.myredclass { color:red; }
Now any html tag that references myredclass as the class, will be affected.

You can also reference multiple classes in one html tag, lets say you have a class (named .bold) that makes text bold, and another class (.red) that makes text red, you just seperate the names of the class when you are referencing them in the class property of your html tag:
<p class="bold red">
now this paragraph will reference both the .bold and .red classes.

Using ID selectors
When you write html its often a good idea to give elements an id, such as <div id="header">. Its not only good for adding javascript, but its easy to make your own css rules for it as well. All you have to do is name your selector with a prepending #. Take this example:

The HTML:
<div id="header"> A red div element! </div>

The CSS:
#header {
background-color:red;
}



Now on to Lesson 4, where you can learn about some of the basic properties in CSS.




Copyright 2005-2008 Neticulis.com