Computing Magazine

Class and Id

Posted on the 19 January 2014 by Savio Menezes
In CSS you can create your own selectors like class and id.
Class Class selector is used to style group of elements. Each class css property starts with ‘.’ Class is written as follows:  .name of class{ css property 1; . . . css property n } You can also create a class for a particular type of html element. Say you can create class for only paragraphs(<p>).To create such class you have to write html element name for which you are creating class followed by period and then name of the class. html element.name of class{ css property 1; . . . css property n } Id Id is used to style a single unique element. The name of id you are specifying should be same as id attribute of that element. Each id starts with pound sign (#). CSS properties for a particular id is written as follows: #name of id{ css property 1; . . . css property n } Note: id and class names shouldn't start with a number.
Example <html>
<head>
<title>Class and Id demo</title>
<style type="text/css">
.even{
text-align:right;
color:red;
}
.odd{
text-align:left;
color:blue;
}
p.mar{
text-align:center;
color:maroon;
}
.end{
color:green;
}
#par{
text-align:center;
color:navy;
}
</style>
</head>
<body>
<h1 style="text-align:center">Class and Id demo</h1>
<p class="odd">This is paragraph 1</p><br/>
<p class="even">This is paragraph 2</p><br/>
<p class="odd">This is paragraph 3</p><br/>
<p class="even">This is paragraph 4</p><br/>
<p class="mar">This is paragraph</p><br/>
<a href="http://saviosteaching.blogspot.com" class="odd">Go to home page</a>
<p id="par">
This is the paragraph on whom par selector is used.
</p>
<p style="text-align:center">This <span class="end">example</span> ends here.</p>
</body>
</html> You can view output here
Explanation: In above example I have created four classes odd, even, mar and end. Odd, end and even classes can be used to style any elements but mar class can be used to style only paragraphs. In this example I have also used id selector (par).
Span and Div Span and div are html elements that are only used to apply style for html code inside them. Span starts with <span> and ends with </span>. Div starts with <div> and ends with </div>. Span is used to style small html code like line or words whereas div is used to style large html code like paragraphs. 

Back to Featured Articles on Logo Paperblog

Magazines