- Комментарии в CSS
- Кратко
- Пример
- Как пишется
- Как понять
- Ещё пример
- Подсказки
- На практике
- Егор Левченко советует
- Алёна Батицкая советует
- How to Comment in CSS
- Familiarize yourself with the CSS comment code.
- Use the comment in the CSS sections of your code.
- Use comments to prevent code from being run.
- Use comments to explain potentially confusing code.
- Use comments to create documentation within the code.
- Use invalid CSS to create temporary single-line comment.
- CSS Comment Tutorial
- CSS Comment Syntax
- Single Line CSS Comment
- Multiline/Block CSS Comment
- Inline CSS Comment
- CSS Comments
- CSS Comments
- Example
- Example
- Example
- HTML and CSS Comments
- Example
- My Heading
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Комментарии в CSS
Нужно что-то скрыть, но не удалять? Хотите оставить пояснение или подсказку? Вам нужен комментарий.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Комментарии в CSS нужны, чтобы комментировать отдельные куски кода или быстро временно отключать свойства без удаления их из кода.
Комментарии не влияют на работу остального кода, а значит невозможно увидеть их, не заглядывая в файл со стилями.
Часто комментарии используются для визуального отделения блоков стилей друг от друга. Например, чтобы отделить стили для шапки сайта от стилей для остальной страницы.
Пример
Скопировать ссылку «Пример» Скопировано
В CSS существует только один вид комментариев, но их можно записывать по-разному.
/* Комментарий-блок, если нужно расписать что-то подробно.*/ .block /* Комментарий в строку */ text-align: center;>
/* Комментарий-блок, если нужно расписать что-то подробно. */ .block /* Комментарий в строку */ text-align: center; >
Обратите внимание, что комментарий вида / / в начале строки в CSS не поддерживается, он работает только в препроцессорах, вроде Sass или Less.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Комментарий оформляется при помощи двух пар символов, /* и * / :
/* Любой текст */
/* Любой текст */
По желанию или в соответствии с принятым в вашей команде стилем кода после открывающих символов можно перенести текст на новую строку, и закрывающую пару тоже поставить на следующей новой строке. Как-то так:
/* Я помню чудное мгновенье: Передо мной явилась ты, Как мимолетное виденье, Как гений чистой красоты.*/
/* Я помню чудное мгновенье: Передо мной явилась ты, Как мимолетное виденье, Как гений чистой красоты. */
Как понять
Скопировать ссылку «Как понять» Скопировано
У комментария обязательно должны быть начало и конец. Открывать комментарий нужно при помощи /* , а закрывать — при помощи зеркальной конструкции * / .
Ещё пример
Скопировать ссылку «Ещё пример» Скопировано
Как выглядит закомментированное свойство:
.block /* height: 100%; */ width: 100%;>
.block /* height: 100%; */ width: 100%; >
А вот так можно закомментировать целый блок:
/* .block width: 100%; height: 100%;> */
/* .block < width: 100%; height: 100%; >*/
Иногда комментариями обозначают начало и конец смысловых блоков стилей:
/* Header */.header display: flex;>/* End Header*/ /* Footer */.footer background-color: pink;>/* End Footer */
/* Header */ .header display: flex; > /* End Header*/ /* Footer */ .footer background-color: pink; > /* End Footer */
В таком коротком куске кода комментарии избыточны и смотрятся грязно. Но когда файл со стилями состоит из тысяч строк (такого, конечно, стоит избегать), то такая навигация удобна.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Не злоупотребляйте комментариями. Не стоит пояснять всё подряд. Пишите комментарии только там, где без подсказки никак не понять, что происходит.
💡 Но и не игнорируйте комментарии. Не молчите там, где есть что сказать. Например, вы использовали !important в коде (напомним, что это крайне нежелательная практика), но в данном случае он необходим. Поясните своё решение, чтобы следующий разработчик всё не сломал, удалив нежелательный элемент.
💡 Чтобы быстро закомментировать или раскомментировать текущую строку или выделенный блок кода, в большинстве редакторов кода можно нажать Ctrl / или Cmd / .
На практике
Скопировать ссылку «На практике» Скопировано
Егор Левченко советует
Скопировать ссылку «Егор Левченко советует» Скопировано
🛠 Иногда в процессе разработки нужно быстро проверять какую-то гипотезу. Не хочется сгоряча удалять блок кода, вымученного кровью и потом. Просто закомментируй подозрительные строки. Если причина не в них, то раскомментируешь. Удалить всегда успеешь.
🛠 Удаляй все закомментированные свойства перед деплоем — публикацией проекта. Комментарии — утилитарная штука. Они полезны, но сильно загружают код и затрудняют его чтение. Если это не информационные комментарии, а следы экспериментов — удаляй их.
🛠 Иногда можно встретить в начале файла своеобразное оглавление, поясняющее в какой части файла искать стили для того или другого блока. Если у вас очень большой файл, то стоит попробовать такой подход. Он может оказаться удобным.
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 Как всегда, стоит удалить все те комментарии, которые не должен видеть заказчик или пользователь конечного продукта, перед деплоем. Все, что неактуально, решено, касается внутренних процессов в вашей компании и не будет использоваться в дальнейшем — смело под нож!
How to Comment in CSS
wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 18 people, some anonymous, worked to edit and improve it over time.
The wikiHow Tech Team also followed the article’s instructions and verified that they work.
This article has been viewed 51,065 times.
Using comments while writing CSS code is helpful for both you and anyone else that may work on or learn from the code. You can use comments to explain potentially confusing functions, quickly prevent blocks of code from being run, and create documentation for the code’s features and purpose. You don’t need to comment for every piece of code that you write, but good commenting can help everyone involved.
Familiarize yourself with the CSS comment code.
CSS uses the C-like «comment block»-style comments /*—*/ . This allows for multi-line comments, and you can quickly use it to disable portions of your code. [1] X Research source
/* Everything between the starting and ending tags will be a comment */
Use the comment in the CSS sections of your code.
Only the parts of your page that are processed as CSS will support the comments. This means they will work in your CSS style page, as well as the block of your HTML page. They will not work on other parts of the HTML page. If you need to comment in a HTML block, use HTML comments.
DOCTYPE html> html> head> style> p color: #93B874; /*You can create comments at the end of lines */ /* Or you can create comments between lines */ font-family: "times"; > /* You can create multi-line comments. Everything between the two comment tags will not be processed when displaying the page */ style> head> body> p> This is a standard HTML paragraph. The comments above will not appear on the page. p> body> html>
Use comments to prevent code from being run.
One of the more important uses for comments is to prevent pieces of code from being processed. This is great for testing changes and debugging code.
style> p color: #93B874; /* font-family: "times"; */ > /* The comment tags above will prevent the "font-family" attribute from being applied */ style>
Use comments to explain potentially confusing code.
You don’t need to comment every line of code, but it’s useful to include comments for code that may not be obvious. This not only helps people who may be collaborating or learning from your code, it can also help you remind yourself about the function of the code.
style> img opacity: 0.5; filter: alpha(opacity=50); /* For IE6-8 */ > /* The comment above indicates that the code on that line is for Internet Explorer 6, 7, and 8 */ style>
Use comments to create documentation within the code.
You can create detailed documentation for your code using CSS comments and other characters. This allows you to explain the function of the program and provide instructions for other coders/users. CSS compression will automatically strip this out when it comes time to run the code, so you don’t have to worry about length affecting the size of the file. [2] X Research source
/*********************************** ************************************ This Makes for a Good Title Header ************************************ ***********************************/ /*========Section Heading=========*/ /*------Sub-Section Heading-------*/ /*This can be the text for each of * for each of your paragraphs. * Adding an * to the beginning of * each line makes it a little easier * for the reader to parse */
Use invalid CSS to create temporary single-line comment.
CSS doesn’t have a «single-line» comment function, like // in JavaScript. You can, however, use invalid CSS at the beginning of a line to keep the following function from being processed. This isn’t considered good practice for major debugging, but it can be useful in a quick pinch. [3] X Research source
style> p color: #93B874; XXXXfont-family: "times"; > /* The "XXXX" above will prevent "font-family" from being processed. Code hacks like this should not be left on a live website, as they could potentially cause problems for the reader */ style>
CSS Comment Tutorial
CSS or Cascade Style Sheets provides the comment mechanism in order to explain the CSS code, code blocks, and different implementations in a CSS code. The CSS comments are omitted by the web browsers and not interpreted as CSS code and they only used for explanation for the CSS code.
CSS Comment Syntax
The syntax of the CSS comment is like below where it starts with /* and ends with */ .
CSS_CODE /* COMMENT */ CSS_CODE
- CSS_CODE is the CSS code which is interpreted and executed by the web browser.
- /* is the start of the comment.
- */ is the end of the comment.
- COMMENT is the comment which can be letter or number or special signs except comment start and end signs.
Single Line CSS Comment
The most popular comment type for the CSS is the single-line CSS comment. The comment consists of only a single line. These single-line comments are used to explain simple things or little code. The /* is used to set the start of the single-line comment. The */ is used to set the end of the comment. If one of the start or end of the comment specifiers missed this creates an error. In the following example, we explain the paragraph selector p and related color CSS code with a single-line CSS comment.
/* This is a single-line comment */ p < /* Color set as blue */ color: blue; >
Multiline/Block CSS Comment
In some cases we may need to create and comment multiple lines. This can be useful if there is lot things to explain or depict in a clear way. The multiline/block comments can be create by using the /* and */ signs where they wrap multiple lines. The characters between comment start and end sign are interpreter as CSS comment and not interpreted as CSS comment. the syntax of the Multiline/Block CSS comment is like below.
CSS_CODE /* Multiline Comment Multiline Comment Multiline Comment */ CSS_CODE
h1 < color: blue; >/* This is a multiline comment This is a block comment This is multiline and block comment */ h2
Inline CSS Comment
Inline comments are to explain specific CSS line after the CSS statement. Both the CSS statement and CSS comment put at the same line or inline.
CSS Comments
CSS comments are not displayed in the browser, but they can help document your source code.
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a later date.
Comments are ignored by browsers.
A CSS comment is placed inside the element, and starts with /* and ends with */ :
Example
You can add comments wherever you want in the code:
Example
Comments can also span multiple lines:
Example
/* This is
a multi-line
comment */
HTML and CSS Comments
From the HTML tutorial, you learned that you can add comments to your HTML source by using the syntax.
In the following example, we use a combination of HTML and CSS comments:
Example
My Heading
Hello World!
This paragraph is styled with CSS.
CSS comments are not shown in the output.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.