Nathan B Hankes
Posted on November 10, 2020
Introduction
This page provides a definition of the CSS selector and lists the various ways to select an HTML element from within the CSS style sheet.
Prerequisites
A basic understanding of HTML
Understanding CSS Selectors
CSS selectors define the HTML elements to which CSS properties apply. In the following CSS syntax, the selector is used to define an HTML element to which the { property: property value } pair, or declaration, applies.
selector {
property: property value;
}
In the below example, we have placed div in the selector position, meaning the { property: property value } pair that follow applies to all div elements within the linked HTML file.
div {
background: red
}
In the above example, we've assigned a background color of red to all div elements within the linked HTML file.
Selecting HTML Elements
There are multiple ways to select an HTML element from the CSS style sheet. Each method has it's own unique syntax.
- Universal Selector: The asterisk (*) selector applies to the entire document
- Type Selector: Applies to all HTML tags of a given type. For example, the div selector will apply to all div tags
- Class Selector: The .myClassName selector will apply to all HTML elements with an attribute of class="myClassName"
- ID Selector: The #myIdName selector will apply to all HTML elements with an attribute of id="myIdName"
- Attribute Selector: The [attribute] selector will apply to all elements with that attribute.
There are ways to select HTML elements more specifically by combining more than one selector. These methods will be covered in the CSS Specificity tutorial.
Understanding Inheritance
HTML elements can inherit CSS { property: property values } pairs, known as declarations, even if they are not specifically selected in the style sheet. For example, if the index.html file had this:
<div>
<p>Welcome to #Vetswhocode</p>
<div>
And the linked stylesheet.css file had the following code:
* {
font-family: sans-serif;
}
div {
font-size: 24px;
}
Since the * selector applies to the entire document, the { font-family: sans-serif } declaration will apply to the paragraph tag.
Additionally, since the paragraph tag is nested within the div tag, the { font-size: 24px } declaration applies to this paragraph element.
Conclusion
You've just learned of different ways to select an HTML element from within your CSS style sheet file.
Posted on November 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 23, 2024