Selectors
A selector points to an element or group of elements to which styles will be applied. There are different types of selectors, based on the type of element or group of elements that they point to.
The syntax of a selector consists of two main parts, a selector and a declaration block that is put in curly brackets:
selector {
property: value;
}
You can write multiple selectors separated by commas, and all styles specified in the declaration block will be applied to them. For example:
selector1, selector2 {
color: red;
}
Declaration block
Declaration blocks contain one or more declarations separated by semicolons. Several declarations look like this:
div {
width: 500px;
height: 50px;
color: yellow;
}
In this example, three styles are applied to <div>
elements simultaneously: specify width equal to 500 pixels, change the height value to 50 pixels, and make the entire text yellow.
Each declaration includes a CSS property name
and a value
separated from each other by a colon.
The property name determines what exactly will be altered: background, text color, position on the page, or something else. The value of a property is a kind of refinement of what it will be changed to. Each property has its own individual set of permissible values.
Types of Selectors
Type selectors
The CSS type selector matches elements by node name. In other words, it selects all elements of the given type within a document. For example:
/* All <h1> elements. */
h1 {
color: red;
}
Class selectors
The class selector matches elements based on the contents of their class
attribute. It is useful when you need to give a lot of different elements the same look.
/* All elements with class="spacious" */
.spacious {
margin: 2em;
}
Id selectors
The Id selector matches an element based on the value of the element's id
attribute. It is used if you need to work with a specific element.
/* The element with id="demo" */
#demo {
border: red 2px solid;
}
Attribute selectors
The CSS attribute selector matches elements based on the presence or value of a given attribute.
/* <a> elements with a title attribute */
a[title] {
color: purple;
}
/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"]
{
color: green;
}
/* <a> elements with an href containing "example" */
a[href*="example"] {
font-size: 2em;
}