Introduction to CSS selectors
Whether you're new to CSS or are a seasoned pro looking to refresh your knowledge, this guide to CSS selectors is for you.
CSS selectors form the basis of Cascading Style Sheets, allowing us to target specific elements within a HTML document and apply style.
Whether you're new to CSS or are a seasoned professional looking to refresh your knowledge, this guide to CSS selectors is for you.
Selector syntax
As you probably know, CSS has a particular syntax they require in order to be understood by web browsers:
The selector describes the element(s) you would like to change. The property describes the which aspect of the element you would like to alter (e.g., color, height, font-family), and the value provides how you would like it to change (e.g., a color, number of pixels, or typeface).
Element selectors
Element selectors are the most basic CSS selectors you can use: they can be used to target specific elements within a page. For example, the example below would make all paragraph text in your document red:
p {
color: red;
}
Descendant selectors
Descendant selectors can be used to select specific elements within another element. For example, to select all list items in an unordered list in your HTML document, you could use the following descendant selector:
ul li {
border-bottom: 1px gray solid;
}
And you can mix and match the selectors below with other types of selector, too!
Classes and IDs selectors
Class and ID selectors are used to select elements which have a specific class or ID value assigned to them. For example, to select all elements in a HTML document with a class of 'spaghetti', you could use the following class selector:
.spaghetti {
background-color: green;
}
Similarly, to select an element in your document with an ID of 'fusilli' you can use the following syntax:
#fusilli {
background-color: yellow;
}
It's worth noting that, in valid HTML, no two elements should have the same ID (that's why it's an ID: it's a unique value for that element!), and many frontend web developers avoid using IDs in your CSS selectors.
These are a type of attribute selector, but have their own syntax as they were historically the primary way we target elements in CSS.
Chained CSS selectors
Chained CSS selectors allow you to target elements in your HTML document with two or more classes assigned to them. For example, to select all elements with a class of both 'spaghetti' and 'penne':
.spaghetti.penne {
background: blue;
}
Note that there is no space character between the two classes above (otherwise you would be creating a descendant selector).
Adjacency selector
Adjacency selectors allow you to target elements which are adjacent (next to) each other. For example, to select all paragraphs which directly follow a h1 element, you could use the following CSS:
h1 + p {
color: blue;
}
The adjacency selector selects the second element listed only if it is directly next to the first element in your HTML document, and does not take effect if there is another element inbetween.
General sibling selectors
General sibling selectors work a little like adjacency selectors described above, only with a more generic scope. Imagine the following HTML in your document:
<article>
<p>Spaghetti</p>
<p>Fusilli</p>
<div>Penne</div>
<p>Tagliatelle</p>
</article>
Using the following general sibling selector selects all but the first paragraph within the article element:
article p ~ p {
color: red;
}
Child selectors
CSS child selectors can be used to target only the first-level child element within nested elements:
ul > li {
font-weight: bold;
}
This is useful if you have nested elements such as in a dropdown menu contained within an unordered list (ul) element, and only want to style the first level list items.
Attribute selectors
Attribute selectors are an intensely powerful way of targeting elements with specific attributes, and there are quite a few ways to match elements with attribute selectors.
Firstly, you can match an element which has a particular attribute (even if that attribute has no value) using this syntax:
input[style] {
display: inline;
}
The above example would match all input elements of any type which have a style attribute.
You can also match elements which have an attribute with an exact value using the following CSS syntax:
input[type="password"] {
background: yellow;
}
You can use the next attribute selector syntax to match elements which have an attribute which contains an exact value, where the values are separated by space characters.
This can be useful to match a specific attribute value where there are multiple classes on an element, such as in this example which selects all div elements in your HTML document which have a title attribute containing 'spaghetti':
div[title~="spaghetti"] {
width: 20%;
}
Similarly, the next attribute selector can be used to match elements with attribute values separated by hyphen characters. This is particularly useful if you want to select elements in a particular root language. The below example matches all paragraphs in English, whether it is American English, British English, Australian English or any other variant.
p[lang|="en"] {
color: green;
}
The prefix attribute selector allows you to select attribute values which begin with a certain value. The example below will select all div elements in your HTML document which have a class which starts 'col':
div[class^="col"] {
margin: 0 1%;
}
The suffix attribute selector gives you the power to select elements which have an attribute value ending with a particular phrase. This can be useful to select all links in your HTML documents to PDFs, for example:
a[href=$=".pdf"] {
background-image: url("pdf.png");
}
Finally, the wildcard attribute selector allows you to select elements with an attribute value which matches at least once in the attribute. The example below will match any link element which contains 'spaghetti' in the href attribute:
a[href*="spaghetti"] {
font-size: 1.25rem;
}
As you can see, there are a wide range of CSS selectors to choose from, and CSS4 looks set to introduce many new selectors to give you a greater choice when selecting elements.
Words: Richard Carter
Richard Carter is a web designer and frontend web developer based in Newcastle upon Tyne, UK. Earl Grey tea and Lego addict.
Like this? Read these!
- How to start a blog
- The best photo editors
- The designer's guide to working from home
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.