Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Basic CSS Selectors | Section
CSS Fundamentals

bookBasic CSS Selectors

メニューを表示するにはスワイプしてください

To apply styles, you need to tell CSS which HTML elements to target. This is done using selectors. In this chapter, we focus on the three most important selectors: the tag selector, the class selector, and the id selector.

Tag Selector

A tag selector targets all elements of a specific HTML tag.
Example HTML:

<p>It was all in my head.</p>

Example CSS:

p {
  color: purple;
  font-size: 36px;
  background-color: pink;
}

This rule applies to every <p> element on the page.

Use tag selectors when you want consistent styling for all elements of that type.

index.html

index.html

styles.css

styles.css

copy

Class Selector

A class selector targets elements that share the same class name.
HTML:

<p class="text">This song is another hit.</p>

In the CSS, reference the class name with a period (.) to define the styles:

.text {
  color: red;
  font-size: 24px;
  background-color: wheat;
}

Only elements with class="text" receive these styles.

Class selectors are the most commonly used selector type in real projects because they allow flexible and reusable styling.

index.html

index.html

styles.css

styles.css

copy

Multiple Classes

An element can have more than one class.
HTML:

<p class="text font">We test multiple class names</p>

CSS:

.text {
  color: navy;
}

.font {
  font-size: 24px;
}

If an element has both classes, it receives styles from both selectors.

This makes class-based styling powerful.

index.html

index.html

styles.css

styles.css

copy

The <p> element with both text and font classes receives styles from both selectors. The text class sets the color to navy, and the font class sets the font size to 24px.

ID Selector

An ID selector targets one unique element.

In the HTML, add an id attribute to an element:

<p id="title">Choose from different themes.</p>

In the CSS, reference the ID with a hashtag (#) to define the styles:

#title {
  font-weight: 500;
  font-size: 20px;
}

IDs must be unique within a page.

Although IDs can be used for styling, classes are usually preferred for consistency and reusability.

index.html

index.html

styles.css

styles.css

copy

1. Select all possible ways to target this element:

2. What is the way to target and style the HTML element with class="navigation-link"?

question mark

Select all possible ways to target this element:

すべての正しい答えを選択

question mark

What is the way to target and style the HTML element with class="navigation-link"?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  3
some-alt