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>
In this HTML document, the CSS selector p
selects both the <p>
(paragraph) elements.
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>
In this document, the CSS selector .btn-primary
selects the button with the btn-primary
class.
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>
In this document, the CSS selector #first
targets the paragraph with the id first
.