CSS Basic Selectors

CSS Basic Selectors

As the name suggests, CSS basic selectors are the simplest and most fundamental selectors for identifying web elements based on straightforward criteria. These include:

1. Element Selector

The element selector targets all instances of a specific HTML tag. Its syntax is simply the tag name, like tagName. For example:

<!DOCTYPE html>
<html>
  <body>
    <h1>This is my heading.</h1>
    <p>This is my first paragraph.</p>
    <p>This is my second paragraph.</p>
  </body>
</html>
HTML code preview

In this HTML document, the CSS selector p selects both the <p> (paragraph) elements.

The target elements are outlined with blue boxes.

2. Class Selector

The class selector targets all elements that share a specific class attribute. The syntax is .className. For example:

<!DOCTYPE html>
<html>
  <body>
    <button type="button" class="btn-primary" onclick="alert('First')">
      First
    </button>
    <button type="button" class="btn-default" onclick="alert('Second')">
      Second
    </button>
  </body>
</html>
HTML code preview

In this document, the CSS selector .btn-primary selects the button with the btn-primary class.

The target element is outlined with blue box.

If an element has multiple classes, you can target it by combining the class names. Each class name is preceded by a dot, with no spaces between them. For example:

<button type="button" class="btn btn-primary" onclick="alert('First')">
  First
</button>

To target this button, the CSS selector would be .btn.btn-primary.

3. ID Selector

The ID selector targets a specific element with a unique id attribute. Its syntax is #idName. For example:

<!DOCTYPE html>
<html>
  <body>
    <h1>This is my heading.</h1>
    <p id="first">This is my first paragraph.</p>
    <p>This is my second paragraph.</p>
  </body>
</html>
HTML code preview

In this document, the CSS selector #first targets the paragraph with the id first.

The target element is outlined with blue box.