CSS Id and Class




CSS id and class are both used to define properties of a HTML tag. CSS id and CSS class are commands used to give a "name" to a certain CSS format.

CSS Class

Class selector is used to specify a style for a HTML elements. Class selectors are created by typing a " . " followed by the class name.

If you want to change a paragraph style, for example font size to 14px and color to red, code will be:

CSS code
.classname {
	font-size:14px;
	color:red;
}

Or Internal Style:

<style type="text/css">
.classname { font-size:14px; color:red; }
</style>

Note the "." before the name you want to use for it.

Now, you can add class="classname" to any element and it will be formatted as such.

HTML code:

<p class="classname">something inside in a paragraph tag</p>

<div class="classname">something</div>

Another example: CSS code:

.classname p {
	font-size:14px;
	color:red;
}

HTML code:

<div class="classname">
<p>something</p>
</div>

In this case p selector in the CSS is overwritten by .classname p, so the font size of any p tag within a parent with a class of classname will be 14px and text color red.

CSS ID

Selector ID is almost the same as a class, so can be styled in the same way. There is one difference between class and id: Id can only be used once per page.

For use CSS ID, the code is the same as a class, but with hashes ( # ) in place of the dots.

#idname {
font-size:14px;
color:red;
}

Now, you can add ID="idname" to any element and it will be formatted as such.

<p id="idname">something</p>

Interesting: you can link to ID with anchor tags. Look at example:

<div id="top"></div>

<a href="#top">Back to top</a>

Id and class combined

You can use an element's ID with one or several classes as well.

CSS Code:

#header {
	background-color: silver
}

.about { color: white; }
.contacts { color:blue; }

HTML Code:

<div id="header" class="about">something</div>
<div id="header" class="contacts">something</div>

Important: always start your class and id names with a alphabetic character, not a number or a non-alpha character