Skip to content

Latest commit

 

History

History
173 lines (119 loc) · 3.06 KB

02.css-selectors.md

File metadata and controls

173 lines (119 loc) · 3.06 KB

CSS selectors are like a set of instructions used to find and style HTML elements on a web page. Imagine you have a group of boxes, each with different labels on them. If you want to paint all boxes with a certain label, you'd first identify those boxes using their labels. In CSS, these labels are akin to selectors.

When you write CSS code, you use selectors to tell the browser which HTML elements (like paragraphs, headings, or links) you want to apply styles to. For example:

  • If you use the selector p, you're telling the browser to apply the style to all <p> (paragraph) elements.
  • If you use a class selector like .blue-text, you're targeting all elements with the class blue-text.
  • An ID selector like #header targets the element with the specific ID of header.

In short, selectors are the part of CSS that help you choose which parts of your webpage to style. They're the first step in the process of making your website look the way you want it to.

1. Type Selector (Element Selector)

Selects all elements of a specified type.

HTML Example:

<p>This is a paragraph.</p>
<h1>This is a heading.</h1>

CSS Example:

p {
  color: blue;
}

h1 {
  font-size: 20px;
}

2. Class Selector

Selects all elements with a specified class attribute.

HTML Example:

<div class="box">Box 1</div>
<div class="box">Box 2</div>

CSS Example:

.box {
  border: 1px solid black;
}

3. ID Selector

Selects a single element with a specified id attribute.

HTML Example:

<div id="unique-element">Unique Element</div>

CSS Example:

#unique-element {
  background-color: yellow;
}

4. Descendant Selector

Selects all elements that are descendants of a specified element.

HTML Example:

<div>
  <p>Paragraph inside a div.</p>
</div>
<p>Paragraph outside a div.</p>

CSS Example:

div p {
  color: green;
}

5. Child Selector

Selects all elements that are the direct children of a specified element.

HTML Example:

<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
</ul>

CSS Example:

ul > li {
  font-weight: bold;
}

6. Adjacent Sibling Selector

Selects an element that is directly after another specific element.

HTML Example:

<div>First div</div>
<p>Adjacent paragraph to the first div.</p>
<p>Another paragraph.</p>

CSS Example:

div + p {
  color: red;
}

7. Attribute Selector

Selects elements based on the presence or value of a given attribute.

HTML Example:

<input type="text" /> <input type="checkbox" />

CSS Example:

input[type="text"] {
  background-color: lightgrey;
}

8. Pseudo-Class Selector

Selects elements based on their state or relation to other elements.

HTML Example:

<a href="https://example.com">Link</a> <input type="checkbox" checked />

CSS Example:

a:hover {
  color: red;
}

input:checked {
  outline: 2px solid blue;
}