.classname vs .clasname #id vs .classname#id

  1. .classname:

    • This selector targets all elements with the class classname.

    • Example:

      <div class="classname">This div will be styled</div>
      <p class="classname">This paragraph will also be styled</p>
      .classname {
        color: green;
      }

      Both the <div> and the <p> elements will have their text color set to green because they both have the class classname.

  2. .classname #id:

    • This selector targets an element with the id id that is a descendant of an element with the class classname.

    • Example:

      <div class="classname">
        <p id="id">This paragraph will be styled</p>
      </div>
      <div>
        <p id="id">This paragraph will not be styled</p>
      </div>
      .classname #id {
        color: blue;
      }

      Only the first <p> with the id id will have its text color set to blue because it is a descendant of an element with the class classname.

  3. .classname#id (without a space between the class and id):

  • This selector targets an element that has both the class classname and the id id.

  • Example:

    <div class="classname" id="id">This div will be styled</div>
    <div class="classname">This div will not be styled</div>
    <div id="id">This div will not be styled</div>
    .classname#id {
      color: blue;
    }

    Only the first <div> will have its text color set to blue because it has both the class classname and the id id.

Last updated