ID Selectors in CSS and Using CSS in HTML

Tutorial # 4 :

In Tutorial # 3 we talked about class selectors which are used to apply on particular subset of elements. Lets talk about CSS id selector. CSS ID selector work same like class selectors but there is a little difference they are only used on one element per page.

Now i am going to show this using an simple example

If you want to implement a CSS rule like p#bold {font-weight:bold;}

Using CSS Rule in HTML :

<p id=”bold”> This paragraph is bold </p>

 

Output of Above Discussion :

ID Selectors

Code of above discussion:

If you are copying from here and code isn’t working download code from the end of the post.

<html>
<head><title> Tutorial # 3 Class selectors </title>
<style type=”text/css”>
<!–p#bold {font-weight:bold;}–></style>
</head><body><p id=”bold”> THis paragraph is bold </p></body></html>

 

See Result of above code in Real Time HTML:

See Output

Now the only difference is that you are using # sign when defining CSS rules like above we used p#bold while in class selectors we used p.bold. Now lets move towards more complex example.

Complex Example :

In this example we will be using both “class selectors” and “ID selectors” to differentiate between the syntax of both. we will use id selector to make the heading red. Other CSS features will be assigned to paragraph using “class selectors”.

id-selector-2Code CSS Using in HTML :

If you are copying from here and code isn’t working download code from the end of the post.

This is html code the red line in the html code shows we just used id selector instead of class selector
see output

<html>
<head><title> Tutorial # 4 ID selectors </title>
<style type=”text/css”>
<!–.blue {color:blue}
h1#red {color:red}–></style>
</head><body><h1 id=”red”> This is H1 Heading </h1><p class=”blue”> THis is first paragraph </p><p class=”blue”> This is 2nd paragrpah with <em>emphasized</em> word </p><p> This is 3rd paragraph and this with <em> new emphsized word </em> </p>
</body>

</html>

 

See Output In Real Time HTML :

See Output 2

Why We are using “ID SELECTORS” :
Since we know same Red H1 header can be acheived using a single class selector then why we are using “ID SELECTOR”. ID selectors
are only used when you are only assigning a particular style on a page for example heading , wigets , page title, Navigational side and many more

 Download Code :

Download All Files

See Tutorial#3

See Tutorial#5

 

3 thoughts on “ID Selectors in CSS and Using CSS in HTML”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>