CSS-kommentarer visas inte i webbläsaren, men de kan hjälpa till att dokumentera din källkod.
Kommentarer används för att förklara koden och kan hjälpa när du redigerar källkoden vid ett senare tillfälle.
Kommentarer ignoreras av webbläsare.
En CSS-kommentar placeras i elementet <style>
och börjar med /*
och slutar med */
:
/* This is a single-line comment */
p
{
color: red;
}
Prova själv →
<!DOCTYPE html>
<html>
<head>
<style>
/* This is a single-line comment */
p {
color: red;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>
Du kan lägga till kommentarer var du vill i koden:
p
{
color: red;
/* Set text color to red */
}
Prova själv →
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>
Kommentarer kan också sträcka sig flera rader:
/* This is
a multi-line
comment */
p
{
color: red;
}
Prova själv →
<!DOCTYPE html>
<html>
<head>
<style>
/* This is
a multi-line
comment */
p {
color: red;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>
Från HTML-handledningen lärde du dig att du kan lägga till kommentarer till din HTML-källa genom att använda syntax.
I följande exempel använder vi en kombination av HTML- och CSS-kommentarer:
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red; /* Set
text color to red */
}
</style>
</head>
<body>
<h2>My
Heading</h2>
<!-- These paragraphs will be red -->
<p>Hello
World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are
not shown in the output.</p>
</body>
</html>
Prova själv →
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<h2>My Heading</h2>
<!-- These paragraphs will be red -->
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>HTML and CSS comments are not shown in the output.</p>
</body>
</html>