Selecting Elements with CSS

One fundamental aspect of CSS is selecting elements within an HTML document to apply styles. This is achieved through CSS selectors.

Understanding Basic Selectors

Type Selector

The most straightforward selector targets elements based on their type.

				
					p {
  color: blue;
}

				
			

Class Selector

Targets elements with a specific class.

				
					.highlight {
  background-color: yellow;
}

				
			

ID Selector

Targets a specific element with a unique ID.

				
					#header {
  font-size: 24px;
}

				
			

Universal Selector

Selects all elements on a page.

				
					* {
  margin: 0;
  padding: 0;
}

				
			

Grouping Selectors

Combine selectors to apply the same style to multiple elements.

				
					h1, h2, h3 {
  font-family: 'Arial', sans-serif;
}

				
			

Descendant Selectors

Select elements that are descendants of another element.

				
					article p {
  color: purple;
}

				
			

Combining Selectors with Combinators

Use combinators to refine selections.

				
					div > p {
  font-style: italic;
}

				
			

Selecting by Attribute

Targets elements based on their attributes.

				
					input[type="text"] {
  border: 1px solid #ccc;
}

				
			

Attribute Presence and Substring

Select elements with a specific attribute, regardless of the value, or based on a substring.

				
					input[required] {
  border: 2px solid red;
}

a[href*="example"] {
  color: orange;
}

				
			

Pseudo-classes and Pseudo-elements

Styling Based on State

Apply styles based on the state of an element.

				
					a:hover {
  color: red;
}

				
			

Selecting Parts of Elements

Target specific parts of an element.

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

				
			

Advanced Selectors

:not() Selector

Exclude elements from the selection.

				
					p:not(.special) {
  font-style: normal;
}

				
			

:nth-child() and :nth-of-type()

Select elements based on their position within a parent or of a specific type.

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

div p:nth-of-type(2) {
  font-weight: bold;
}

				
			

:first-child, :last-child, and :only-child

Select the first, last, or only child elements of a parent.

				
					ul li:first-child {
  font-weight: bold;
}

p:only-child {
  color: green;
}

				
			

:focus and :checked Selectors

Style elements in focus or checked state.

				
					input:focus {
  border: 2px solid blue;
}

input[type="checkbox"]:checked {
  background-color: #ffd700; /* yellow */
}

				
			

By understanding these selectors, you possess the tools to precisely style elements and create visually appealing and responsive web designs. As you continue your CSS journey, remember to experiment and combine these techniques for optimal results. Happy Coding! ❤️

Table of Contents