Tech Junkie Blog - Real World Tutorials, Happy Coding!: The ID And Class Selectors in CSS

Friday, August 13, 2021

The ID And Class Selectors in CSS

The most commonly used selectors in CSS are the class and ID selectors. A class in CSS is defined with a . in front of it.  For example you can have class call .rainbow and an ID for a div call rainbow those are two different things.

To apply a style to a class you define the class in the stylesheet as

.rainbow { color: pink; font-weight: bold; font-size:24px;}

Then you would use the class as such in the HTML markup

<p class="rainbow">What color am I?</p>









But if you want to apply style to an id that's used in HTML markup you have to do the opposite.
To reference an id in HTML you have to prefix your CSS style with the # character so in the CSS style you would have the following declaration



#rainbow { color: green; font-weight: bold; font-size:24px;}

<p id="rainbow">I am an ID</p>











You can combine class and HTML element like so

p.error {color:red; font-weight: bold;}

The above style applies the color red to the error class that only applies to the paragraph tag.
This is how you would you would call it on your HTML markup  <p class="error">There's an error!</p>

You can also combine classes like so

        p.error {color:red; font-weight: bold;}
        p.bigError{font-size: 50px;}

Then you can apply both styles at the same time using one p tag by specifying both classes using one p tag

<p class="error bigError">There's a big error!</p>















Here is the full markup

<html>
<head>
    <style>
        .rainbow { color: pink; font-weight: bold; font-size:24px;}
        #rainbow { color: green; font-weight: bold; font-size:24px;}
        
        p.error {color:red; font-weight: bold;} 
        p.bigError{font-size: 50px;}
    </style>
</head>
<body>
    <p class="rainbow">What color am I?</p>
    <p id="rainbow">I am an ID</p>
    
    <p class="error">There's an error!</p>   
    <p class="error bigError">There's a big error!</p>
</body>
</html>

Previous: Target Specific Media Environments With CSS Media And Feature Queries

1 comment:

Search This Blog