Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 6 - CSS Selectors And Properties

6.1 Types Of CSS Selectors

CSS selectors enable you to specify which HTML elements to style. There are different types of selectors, each serving a specific purpose:

  1. Element Selector: Targets all instances of a specified HTML element.

    <style>
    p {
        color: blue;
    }
    </style>
    <p>This is a text.</p>
    

    This CSS block makes all <p> (paragraph) elements display blue text.

  2. Class Selector: Targets elements with a specific class attribute. Classes can be reused on multiple elements.

    <style>
    .intro {
        font-size: 20px;
    }
    </style>
    <p class="intro">This is a text.</p>
    

    Here, the .intro class applies a font size of 20 pixels to any element that has this class.

  3. ID Selector: Targets an element with a specific id attribute. IDs should be unique within a page.

    <style>
    #mainHeader {
        color: green;
    }
    </style>
    <h1 id="mainHeader">This is a Heading</h1>
    

    This CSS rule makes the element with the id mainHeader have green text.

  4. Universal Selector: Targets all elements on a webpage.

    <style>
    * {
        margin: 0;
        padding: 0;
        color: red;
    }
    </style>
    <h1>This is a heading.</h1>
    <p>This is a text.</p>
    

    Here, * selects all elements and sets their margins and padding to zero, with red text color.

  5. Attribute Selector: Targets elements based on the presence or value of a given attribute.

    <style>
    a[target="_blank"] {
        color: red;
    }
    </style>
    <a href="https://google.com" target="_blank">Google</a>
    

    This CSS selector makes all links (<a> tags) that open in a new tab (target="_blank") have red text.

Understanding these CSS selectors gives you powerful tools to precisely style elements on your webpage. We'll explore each of these in more detail in upcoming lessons.