CSS Selectors Tutorial – Types, Syntax, and HTML Examples

CSS selectors target HTML elements so CSS rules apply only where they should. Use type, class, ID, attribute, group, combinator, and pseudo selectors to style elements by name, state, position, relationship, or attribute value.

In this tutorial, you will learn how CSS selectors work and how to apply them to select the HTML elements you want to style. You will cover basic selectors, attribute selectors, group selectors, combinator selectors, and pseudo selectors. Knowledge of CSS selectors is useful for front-end developers, web designers, and anyone who works with HTML, XHTML, and CSS.

CSS Selectors with Aspose.HTML for .NET

The examples in this article explain standard CSS selector syntax. Because this tutorial is part of the Aspose.HTML documentation, you can also use the same selector syntax programmatically with QuerySelector() and QuerySelectorAll() in Aspose.HTML for .NET. See Use CSS Selectors in C# for C# examples.

CSS Selector Types

CSS selectors are used to select the HTML elements you want to style and apply a set of CSS rules. There are a few different types of CSS selectors:

The following quick reference shows common CSS selector patterns:

SelectorExampleSelects
TypepAll <p> elements.
Class.noticeElements whose class list contains notice.
ID#headerThe element with id="header".
Universal*All elements.
Attribute[name="email"]Elements whose name attribute equals email.
Compound (AND)button.primary<button> elements whose class list contains primary.
Selector list (OR)h1, h2All matching <h1> and <h2> elements.
Descendantarticle p<p> elements at any depth inside <article>.
Childarticle > p<p> elements that are direct children of <article>.
Pseudo-classa:hoverLinks while the pointer is over them.
Pseudo-elementp::first-letterThe first letter of each paragraph.

Basic Selectors

Basic CSS selectors select HTML elements according to their id, class, type, or all elements on the web page.

Type Selector or CSS Element Selector

The Type Selector or Element Selector specifies to which elements a rule should apply, by naming the type of the element, such as <h1>. In other words, the Element Selector selects HTML elements based on the element name.

CSS

1h1 {
2	text-align: center;
3	color: DarkRed;
4} 

HTML Example

1<h1>Aspose.HTML for .NET</h1>
2<p>Aspose.HTML for .NET is a cross-platform class library that enables your applications to perform a wide range of HTML manipulation tasks.</p>

Rendered result of applying a CSS type selector to an h1 element

ID Selector

The ID Selector selects a specific element using the id attribute of an HTML element. An element will be selected if its id attribute exactly matches the value specified in the ID Selector.

CSS

1#demo {
2  	background-color: #fcded4;
3	font-size: 24pt;
4}

HTML Example

1<p id="demo">This paragraph has a special ID on it!</p>
2<p>This is just a regular paragraph.</p>

Rendered result of applying a CSS ID selector to one paragraph

Class Selector

The Class Selector matches HTML elements with a specific class attribute. You can use the class attribute for all HTML elements that are valid in the body section of an HTML document, including the <body> element itself. To select elements with a specific class, write a dot (.) character, followed by the class name. For example, if we want all elements with a class of "main" to have a different background color, text color and font size we would use the following CSS rule:

CSS

1.main {
2	background-color: #d4e9fc;
3	color: red;
4    font-size: 16pt;
5} 

HTML Example

1<h1>CSS Class Selector</h1>
2<p>The class attribute and its value can be used to create a CSS selector that refers to the selected web element.</p>
3<p class="main">The dot (.) is used to indicate the class attribute to create the CSS Class selector.</p>

Rendered result of applying a CSS class selector to a selected paragraph

Universal Selector

The Universal Selector is used to select all elements on a web page. For example, if we want every element to have a center text-align and blue text color, we would use the following CSS rule:

CSS

1* {
2    text-align: center;
3    color: #0154a2;
4}

HTML Example

1<h1>CSS Universal Selector</h1>
2<p>The Universal Selector selects all elements. The star symbol will target every single element on the page.</p>

Rendered result of applying the CSS universal selector to all elements

Attribute Selectors

CSS Attribute Selectors provide a simple and efficient way to apply styles to HTML elements based on the presence of a particular attribute or attribute value. This is a great way to style HTML elements by grouping them based on certain attributes, and the Attribute Selector will select those elements with similar attributes. You can create an Attribute Selector by putting the attribute in square brackets:

CSS selectorExampleDescription
[attribute][translate]Selects elements that have a translate attribute.
[attribute="value"][translate="no"]Selects elements whose translate value is exactly no.
[attribute~="value"][title~="flower"]Selects elements whose title contains the complete whitespace-separated word flower.
[attribute|="value"][lang|="de"]Selects elements whose lang is de or starts with de-.
[attribute^="value"]a[href^="#"]Selects links whose href starts with #.
[attribute$="value"]a[href$=".html"]Selects links whose href ends with .html.
[attribute*="value"]a[href*="aspose"]Selects links whose href contains the substring aspose.

Select Elements by Name or Text

CSS has no separate name selector. To select elements by the HTML name attribute, use an attribute selector such as [name], input[name], or input[name="email"].

The *= operator searches for a substring in an attribute value; it does not search an element’s text content. Standard CSS does not provide a :contains() selector for matching inner text. To find HTML elements by text in C#, use XPath or select candidate elements and inspect their TextContent. See Extract Text from HTML for examples.

Let’s consider one of the CSS Attribute Selectors as an example:

CSS

1h3[class*="1"] {
2    background-color: #b4e8fd;
3}

HTML Example

1<h3 class="test-1">CSS Attribute Selector</h3>
2<h3>CSS Attribute Selector</h3>
3<h3 class="12">CSS Attribute Selector</h3>

Rendered result of applying a CSS attribute selector to h3 elements

Group Selectors

A selector list applies the same CSS rule to multiple selectors. Separate the selectors with commas, as shown in the following example:

CSS

1h1, h2, h3 {
2    color: #36C;
3    font-family: helvetica;
4}

HTML Example

1<h1>CSS Group Selector (,)</h1>
2<h2>The defined style will apply to h1, h2 and h3 elements.</h2>
3<h3>The order of the list doesn't matter.</h3>

Rendered result of applying a CSS group selector to h1, h2, and h3 elements

Combine CSS Selectors – AND, OR, and &

CSS does not use and or or keywords to combine ordinary selectors. To express AND, write simple selectors together without whitespace. The selector .card.featured matches an element only when it has both classes, while input[name="email"][required] matches an <input> that satisfies both attribute conditions.

To express OR, separate selectors with commas. For example, h1, h2, h3 matches any of the three heading types. The functional pseudo-class :is(h1, h2, h3) provides the same alternatives when they are part of a larger selector, such as article :is(h1, h2, h3).

The ampersand (&) is the CSS nesting selector, not an AND operator. Inside a nested rule, it represents the elements matched by the parent rule:

1.card {
2    padding: 1rem;
3
4    &.featured {
5        border-color: gold;
6    }
7}

Here, &.featured is equivalent to .card.featured. See the CSS Nesting Module for the complete nesting syntax.

Combinator Selectors

Combinator selectors select elements based on the relationship among them. There are four different combinators in CSS: descendant selector (space), child selector (>), adjacent sibling selector (+), and general sibling selector (~):

CSS selectorExampleDescription
element elementdiv pSelects <p> elements that are descendants of a <div> at any depth.
element > elementdiv > spanSelects <span> elements whose direct parent is a <div>.
element + elementdiv + pSelects a <p> that immediately follows a sibling <div>.
element ~ elementdiv ~ pSelects every later sibling <p> that shares a parent with the preceding <div>.

Let’s consider one of the CSS combinator selectors as an example. The child selector (>) selects all elements that are the children of a specified element. Elements matching the second selector must be direct children of elements matching the first selector:

CSS

1div > p {
2	background-color: #d4e9fc;
3}

HTML Example

1<div>
2    <p>CSS Child Selector (>). Paragraph 1 is in a div.</p>
3    <section>
4        <p>Paragraph 2 is in a div but inside a section element. It is not a direct child of the div element that matches the first selector. Therefore, there is no background color!</p>
5    </section>
6</div>
7<p>Paragraph 3 is not in the div at all.</p>

Rendered result of applying a CSS child combinator selector

Pseudo-classes and Pseudo-elements

Pseudo-classes select elements by state, position, or another condition and begin with one colon (:). Pseudo-elements select a specific part of an element and normally begin with two colons (::).

SelectorSelects
a:hoverLinks while the pointer is over them.
input:focusAn input that currently has focus.
input:checkedChecked radio buttons and checkboxes.
option:checkedThe currently selected <option>.
li:nth-child(2)A list item that is the second child of its parent.
p:not(.intro)Paragraphs that do not have the intro class.
article:has(img)An <article> that contains an <img>.
p::first-letterThe first letter of each paragraph.
::selectionText currently selected by the user.

The following example uses the ::first-letter pseudo-element:

CSS

1p::first-letter {
2	font-size: 130%;
3	color: red;
4	font-family: arial;
5}

HTML Example

1<p>Pseudo-Element Selectors</p>
2<p>A CSS Pseudo-Element is used to style specified parts of an element.</p>
3<p>For example, p::first-letter can be used to change the first letter of a paragraph.</p>

Rendered result of applying a CSS pseudo-element selector to the first letter of paragraphs

FAQ

What is the difference between class and ID selectors?

A class selector such as .main can match many elements. An ID selector such as #demo should match one unique element because id values should be unique in an HTML document.

When should I use an attribute selector?

Use an attribute selector when the attribute itself or part of its value identifies the elements you need, such as links ending in .html, elements with translate="no", or images with a specific alt value.

What is the difference between descendant and child selectors?

A descendant selector such as div p matches nested <p> elements at any depth inside a <div>. A child selector such as div > p matches only direct child <p> elements.

Can I use CSS selectors in C# with Aspose.HTML for .NET?

Yes. Aspose.HTML for .NET supports CSS selector queries through QuerySelector() and QuerySelectorAll(). See Use CSS Selectors in C# for programmatic examples.

Related Articles