Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Class Selectors | Selectors and Cascade
Introduction to CSS Part I

book
Class Selectors

A class selector is a type of selector used to select and style elements with a specific class attribute. It is identified by the . symbol followed by the class attribute value.

css
.warning {
background-color: yellow;
color: black;
font-weight: bold;
}
html

index.html

css

index.css

copy
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<p class="warning">Warning! Yellow background!</p>
</body>
</html>

In this example, the class selector is .warning, which is used to select elements with a class attribute of warning. The style rules inside the curly braces will be applied to these elements.

Unlike id selectors, class selectors can select and style multiple elements on a single HTML page. This makes them very useful for creating reusable styles that can be applied to multiple elements.

html

index.html

css

index.css

copy
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 class='warning'>
Warning header
</h1>
<p class='warning'>
Warning paragraph
</p>
<p class='error'>
Error paragraph
</p>
</body>
</html>

In this example, both the .warning and .error selectors are class selectors. They make it easy to style multiple elements on the same page, allowing you to create different styles for different types of messages quickly.

You can also use the class selector and other selectors to create more specific rules.

css
#header .warning {
font-style: italic;
}
html

index.html

css

index.css

copy
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div id="header">
<p>Just a paragraph in a 'header' div</p>
<p class="warning">Warning paragrapgh in a 'header' div</p>
</div>
<p class="warning">Warning paragraph outside of a 'header' div</p>
</body>
</html>

In this example, the #header .warning selector selects all the elements with a class attribute of warning that are descendants of an element with the id attribute of header. This allows you to apply styles to the elements with the " warning " class within the " header " element.

One potential downside of using class selectors is that they can make your CSS code more complex, as you may have to create and maintain multiple class selectors for different styles. However, the ability to reuse styles across multiple elements can make up for this complexity in many cases.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt