CSS Selectors Reference

CSS selectors are powerful tools that allow you to target specific HTML elements and apply styles. This guide will provide an in-depth reference, from basic selectors to advanced ones, ensuring you have a comprehensive understanding.

Basic Selectors

Universal Selector (*)

Targets all elements on the page.

				
					* {
  margin: 0;
  padding: 0;
}

				
			

Type Selector (Element Selector)

Targets specific HTML elements.

				
					p {
  color: blue;
}

				
			

Class Selector (.classname)

Targets elements with a specific class.

				
					.highlight {
  background-color: yellow;
}

				
			

ID Selector (#id)

Targets a specific element with a unique ID.

				
					#header {
  font-size: 24px;
}

				
			

Attribute Selectors

Attribute Presence Selector ([attribute])

Targets elements with a specific attribute.

				
					[target] {
  text-decoration: underline;
}

				
			

Attribute Value Selector ([attribute=value])

Targets elements with a specific attribute value.

				
					[type="submit"] {
  background-color: green;
}

				
			

Attribute Starts With Selector ([attribute^=value])

Targets elements with an attribute starting with a specific value.

				
					[href^="https"] {
  color: blue;
}

				
			

Combinators

Descendant Selector (Whitespace)

Targets nested elements.

				
					article p {
  font-style: italic;
}

				
			

Child Selector (>)

Targets direct children of an element.

				
					ul > li {
  list-style-type: square;
}

				
			

Adjacent Sibling Selector (+)

Targets an element that is immediately preceded by a specified element.

				
					h2 + p {
  font-weight: bold;
}

				
			

Pseudo-classes

:hover

Targets an element when the user hovers over it.

				
					a:hover {
  color: red;
}

				
			

:nth-child()

Targets elements based on their position.

				
					li:nth-child(odd) {
  background-color: #f2f2f2;
}

				
			

Pseudo-elements

::before and ::after

Adds content before or after the selected element.

				
					p::before {
  content: "» ";
}

				
			

::first-line and ::first-letter

Styles the first line or first letter of an element.

				
					p::first-line {
  font-weight: bold;
}

				
			

Advanced Selectors

:not()

Excludes elements from the selection.

				
					li:not(.special) {
  color: gray;
}

				
			

:focus-within

Targets an element if any of its descendants have focus.

				
					form:focus-within {
  border: 2px solid blue;
}

				
			

This CSS Selectors Reference covers a wide range of selectors, from the fundamental to advanced. By mastering these, you can precisely target and style elements in your web pages. Use this guide as a comprehensive resource to enhance your CSS skills and create well-styled, dynamic web designs. Happy coding! ❤️

Table of Contents