In CSS Tutor - lesson 1 we answered the question, "What is CSS?" by looking into some very easy examples. We styled HTML elements by providing styles assiciated with the element, p { font-family: tahoma;};
In lesson 2, we continue with that theme, but we will explore how to add styles that are not bound to a spicific HTML tag. We will be looking at creating styles for ID's and for CSS styles for classes.
As you might have guessed, a class is a group of items which share certain characteristics (in this case styling characteristics. An ID applies to single elements. The use of both ID's and classes is very very similar to styling, with one important difference. In lesson 1, we added style information to the style sheet (.css file) and we then used our normal HTML tags. With ID's and classes, we have to add the class name or ID to the tag.
As an example, if I wanted to make text red using CSS, I could use the following code in my CSS file:
.classRedText { color: red; }
In my HTML file, I could use this class like this: <p class="classRedText">This is my first paragraph</p>
ID's work in the same way, ie:
#idBlueText { color: blue; }
<p id="idBlueText">This is my second paragraph</p>
You will notice that here, we included either the id="idname", or class="classname" attribute to the HTML tag. Also note that in the CSS file, the ID is preceeded by a #, whereas class names are preceeded with a period(.). Take a look at Example 1. Notice in this example, that because we did not use the style info with a tag element, the text in the paragraph with no style class or id is formatted as its default black text.
Example 2 is a slight expansion of example 1. The unformatted text in example 1 is now formatted here too. We have added the p { color: yellow; } tags here. This means that text found in the p tags will be yellow. But, this is not the case in this example. The reason is that putting an ID or class in an element over-rides the p element style.
Well, when we said that the ID or class identifiers over ride the HTML element style, this is not exactly 100% accurate. We should have said, the ID or class identifier's style will over ride the same styles in the HTML element styles. Huh? What this means is that if in my HTML Style I say, "color: yellow", then in my ID or class I say "color: red;", then the color will be red because it was over ridden. However, if in my HTML style, I say "color: yellow;", then in my ID or class I say "font-weight: bold;", in this case, the values are not over riden, and they will both be used, ie, you will have bold, yellow text. Take a look at Example 3 to see what we're talking about.
Please sign up for our Mailing List to stay updated with our latest blog posts and tutorials.
|