IDs and Classes

Introduction: This is the second part in my CSS Styling tutorials, in which I will tell you about IDs and Classes. What Are IDs? The Identification names are one option to link the HTML elements to the relevant CSS styling options. One alternative to this is using Classes - which I cover after this. Giving HTML Elements IDs: To give an HTML element an ID, all we do is set the attribute within the opening tag, just like any other attributes...
  1. <p id='MyID'>Hi</p>
Styling IDs: To style IDs, all we need to do is use a hashtag/pound sign (#) before the ID name, followed by two (one opening, and one closing) curley braces ({ and }) with the stying inbetween the two curley braces...
  1. #MyID {
  2. //Styling for the ID of MyID goes here.
  3. }
Classes: Classes are essentially the exact same as IDs, however a fullstop/dot (.) is used to signify the styling is for a Class as opposed to an ID... Giving an HTML element a Class:
  1. <p class='MyClass'>Hi</p>
Setting the styling options:
  1. .MyClass {
  2. //Styling for the Class of MyClass goes here.
  3. }
Difference Between IDs and Classes: Although they work exactly the same, they are set the same, and they share the same styling coding, there is one intention behind the two variations of the similar methods; which is that Classes are to be used for multiple elements while IDs are only to be used for single elements. For example: You would give all the paragraphs (

) in your page a Class, but they would all use different IDs (if any). Linking CSS To a HTML Element: To link your CSS to an HTML element (text, div, etc.) you will need to decide whether you want to use a class or id, you will also need a unique name. Once you have those, go to your element in HTML and add...

  1. class='myClass'
... to the attributes of that element if you chose a class, or...
  1. id='myID'
if you chose an id. Make sure you replace 'myClass' and/or 'myID' with your unique name. Then, in the CSS you will want to encase your properties with...
  1. .myClass {
  2. //Properties go here
  3. }
if you chose a class, or...
  1. #myID {
  2. //Properties go here
  3. }
(You can remove the line beginning with // if you wish). Here's an example...
  1. <html>
  2. <head>
  3. <style>
  4. .myClass {
  5. color: blue;
  6. width: 300px;
  7. height: 100px;
  8. //Class of styling.
  9. }
  11. #myID {
  12. color: #000;
  13. width: 300px;
  14. height: 100px;
  15. //ID of styling.
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class='myClass'>This div of text uses a class to style it.</div>
  21. <div id='myID'>This div of text uses an id to style it.</div>
  22. </body>
  23. </html>

Add new comment