Как составить комментарий в html


Загрузить PDF


Загрузить PDF

Комментирование кода не только позволит вам самому понять, что же вы тут наворотили, но и другим существенно облегчит работу с вашим кодом. Кроме того, с помощью комментирования можно быстро отключать те части кода, которые вы еще не закончили, но уже добавили на страницу, что полезно при тестировании. Научитесь правильно комментировать, сделайте жизнь проще себе и окружающим!

Шаги

  1. Изображение с названием 795094 1

    1

    Однострочный комментарий. Такие комментарии оформляются тегами . Такие комментарии можно быстро без особых сложностей, чтобы напоминать себе, что делает тот или иной фрагмент кода.

    <html>
    <head>
    <title>Заголовок</title>
    </head>
    <body>
    <!-- Это абзац -->
    <p>Сайт</p>
    </body>
    </html>
    
    • Главное – без пробелов тут. Например, код < !– не активирует комментарий. Между тегами, впрочем, пробелов можно поставить сколько угодно.
  2. Изображение с названием 795094 2

    2

    Многострочный комментарий. Такие, как понятно из названия, захватывают уже несколько строк, что полезно для объяснения сложных участков или блокирования курпных частей кода.

    <html>
    <head>
    <title>Заголовок</title>
    </head>
    <body>
    <!-- 
    Длинный комментарий.
    Все, что между тегами,
    будет обработано браузером как комментарий.
    -->
    <p>Сайт</p>
    </body>
    </html>
    
  3. Изображение с названием 795094 3

    3

    Используйте комментарии для отключения фрагментов кода. Пытаясь поймать хитрый баг (ошибку), можно использовать комментарии для последовательного перебора кода. Так вам будет куда проще вернуть все обратно – для этого нужно будет лишь удалить код комментария.

    <html>
    <head>
    <title>Заголовок</title>
    </head>
    <body>
    <p>Проверка изображений</p>
    <img src="/images/image1.jpg">
    <!-- Спрячу-ка я это
    <img src="/images/image2.jpg">
    -->
    </body>
    </html>
    
  4. Изображение с названием 795094 4

    4

    Используйте комментарии для предотвращения запуска скриптов в не поддерживающих их браузерах. Если вы пишете на JavaScript или VBScript, то можете с помощью комментариев прятать скрипты от браузеров, которые их все равно не поддерживают. Вставьте тег комментария в начало скрипта, закончите все//–>, чтобы скрипт все же запустился – но лишь в тех браузерах, которые смогут это сделать.

    <html>
    <head>
    <title>VBScript</title>
    </head>
    <body>
    <script language="vbscript" type="text/vbscript">
    <!--
    document.write("Hello World!")
    //-->
    </script>
    </body>
    </html>
    

    [1]

    • Символы // в конце строки не дадут браузеру запустить скрипт, если тот не сможет его выполнить.

    Реклама

Советы

  • Комментируйте почаще, чтобы не запутаться через какое-то время в собственном коде.

Реклама

Об этой статье

Эту страницу просматривали 49 445 раз.

Была ли эта статья полезной?

Adding comments in HTML can help you write and organize the backend of your webpage. They’re so useful that it’s considered a best practice to use them.

two people writing html comments in an office

You can add comments to explain your code, which will make it easier to edit in the future or to work with other developers. You can also use comments to simplify your debugging efforts by “commenting out” lines of code without deleting them.

In this post, we’ll look more closely at what a comment is in HTML, as well as

  • how to write HTML comments
  • how to write multi-line HTML comments
  • how to write inline HTML comments
  • how to “comment-out” in HTML

Download Now: 25 HTML & CSS Hacks [Free Guide]

What is a comment in HTML?

In HTML, a comment is a section of text that is not processed by the web browser. Comments are enclosed in <!– –> tags. These tags tell the browser that the text inside them is a comment and should not be rendered on the front end.

With the comments tag, you can leave notes to remind yourself where you left off in the build process. You could explain the intended functionality of a section of code for another developer or your future self. Or, you might assign someone a task or point out an error for them with a comment.

In short, commenting in HTML helps you work smarter when building or debugging a website. Here’s a video that goes into this in more detail:

Now, let’s look at an example.

How to Write a Comment In HTML

To leave a comment in HTML, place a <!— tag before the code and a –> tag after the code that you want to hide. These tags tell browsers to ignore anything between them.

For example, say you’re building a website with a team of developers. You want to leave a note reminding them that all buttons should use the same color.

Here’s what your HTML might look like, as well as the result on the front end:

See the Pen comment example by HubSpot (@hubspot) on CodePen.

As you can see, the comment is not rendered on the front end.

You can also quickly comment a line of code with the keyboard shortcut Ctrl + / on PC or Command + /. This method is much faster than typing the tags manually.

How to Write a Multi-line Comment in HTML

To create a comment in HTML over multiple lines, you can use the same method — just enclose your target text inside <!– –> tags.

See the Pen comment example – multi-line by HubSpot (@hubspot) on CodePen.

How to Write an Inline Comment in HTML

It’s also possible to leave inline comments between active sections of HTML code:

See the Pen comment example – inline comment by HubSpot (@hubspot) on CodePen.

Commenting Out in HTML

Aside from leaving notes to developers (or your future self), HTML comments also come in handy for “commenting out” sections of code. Commenting out is when you temporarily “deactivate” a piece of working code with a comment.

Commenting out has two main purposes. The first is debugging: Upon discovering an error, you can “deactivate” different parts of your code with comments, check if the error is still occurring, and repeat the process until the buggy code is found.

Here’s what “commenting out” a button from the last example would look like:

See the Pen comment example: commenting out by HubSpot (@hubspot) on CodePen.

The second purpose is saving old versions of your code. Since commenting out means the code will remain visible in the back end, it can be a way of keeping old sections of code for developers who are just joining or have inherited the web project.

Say I run some A/B tests and discover that the button isn’t getting any clicks and I want to remove it. In that case, I could comment it out, leaving a note that a CTA button at the bottom page didn’t convert. Then, the next person who comes along and tries to optimize the conversion rate on the page will know to start with another button placement.

Leaving Comments in HTML

Comments are another way you can “talk” to people in your code. You can add explanatory notes for other collaborators on a web project, or you can leave yourself notes reminding you to come back to a section or prioritize it during your next redesign.

The best part? Comments will not appear on the front end of your site and they’re simple to master, even if you’re just getting started learning HTML.

Editor’s note: This post was originally published in April 2021 and has been updated for comprehensiveness.

coding-hacks

HTML Comment – How to Comment Out a Line or Tag in HTML

In this article, you’ll learn how to add single and multi-line comments to your HTML documents.

You’ll also see why comments are considered a good practice when writing HTML code.

Let’s get started!

The general syntax for an HTML comment looks like this:

<!-- I am a comment! -->

Comments in HTML start with <!-- and end with -->.

Don’t forget the exclamation mark at the start of the tag! But you don’t need to add it at the end.

The tag surrounds any text or other HTML tag you want to comment out.

HTML comments don’t get displayed in the browser. This means that any comments you add to your HTML source code will not be shown when the document gets rendered in a web browser.

That being said, keep in mind that anyone can view the source code of practically every website published on the Internet by going to View -> Developer -> View Source – and this also includes all comments!

So your comments will be visible for others to see if you make the HTML document public and they choose to look at the source code.

Writing comments is helpful and it’s a good practice to follow when writing source code. Comments help you document and communicate about your code and thought process to yourself (and others). It also reminds you what you were thinking/doing when you come back to a project after months of not working on it.

Comments also help you communicate with other developers who are working on the project with you. Your comments can clearly explain to them why you added certain lines of code.

A single-line comment only spans one line. As mentioned earlier, that line will not get displayed in the browser.

Use a single-line comment when you want to explain and clarify the purpose behind the code that follows it or when you want to add reminders to yourself like so:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- Add the navbar here -->
    <h2>About me</h2>
    <p>I am learning to code with freeCodeCamp.</p>
    <p>I am going through each and every one of their awesome and super helpful  certifications. </p>
    <p>I am on my way to becoming a fullstack web developer!</p>
    <h3>Work Experience</h3>
</body>
</html>

Single-line comments are also helpful when you want to make clear where a tag ends. This comes in handy in a long and complex HTML document where a lot is going on and you may get confused as to where a closing tag is situated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <section class="contact">
    </section> <!--closing tag of contact section is here-->
</body>
</html>

You can also add comments in the middle of a sentence or line of code.

Only the text inside the <!-- --> will be commented out, and the rest of the text inside the tag won’t be affected.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>I am <!--going to be--> a web developer</p>
</body>
</html>

Comments can also span multiple lines, using the exact same syntax you’ve seen so far.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>I am  a web developer</p>
    <!--This is going to be my portfolio.
    It will show off the projects that I'm most proud of.
    I could go on and on about what I want to add
    because I am writing a multi-line comment here-->
</body>
</html>

So what if you want to comment out a tag in HTML?

You wrap the tag you’ve selected in <!-- -->, like so:


!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>My portfolio page</h2>
    <h3>freeCodeCamp certification projects</h3>
    <!-- <section class="hero">
    </section>  -->
    <h2>About Me</h2>
</body>
</html>

Commenting out tags helps with debugging.

When something isn’t working the way it’s supposed to or they way you intended it to, start commenting out individual tags one by one. This lets you test them and see which one is causing the issue.

There are shortcuts you can use for adding comments – and you’ll probably end up using them a lot. The shortcut is Command / for Mac users or Control / for Windows and Linux users.

To add a single-line comment, just hold down the combo of keys shown above inside the code editor. Then the whole line you’re on will be commented out. Just keep in mind that since everything will be commented out on that line, this only works for single-line comments. You’ll need to add inline comments manually.

For adding multi-line comments, select and highlight all the text or tags you want to comment out and hold down the two keys shown previously. Each line you selected will now have a comment.

Conclusion

And there you have it – now you know how and why to use comments in HTML!

Learn more about HTML by watching the following videos on freeCodeCamp’s YouTube channel:

  • HTML Tutorial – Website Crash Course for Beginners
  • HTML Full Course – Build a Website Tutorial

freeCodeCamp also offers a free, project-based certification on Responsive Web Design.

It is ideal for complete beginners and assumes no previous knowledge. You’ll start from the absolute necessary basics and build your skills as you progress. In the end, you’ll complete five projects.

Thanks for reading and happy learning 🙂



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Это задание архивной части. Перейдите по ссылке, чтобы пройти актуальную часть.

Комментарий в HTML-коде задаётся так:

<!-- любой текст -->

Текст внутри комментария не отображается браузером на странице. Комментарии обычно используются в следующих случаях:

  • Для комментирования кода. Всегда полезно оставить подсказку.
  • Для временного отключения кода. Удалять код неудобно, так как его надо будет восстанавливать, а закомментировать и потом раскомментировать — самое лучшее решение.

Комментарии можно использовать в любом месте страницы, кроме тега <title> — внутри него они не работают. Внутри тега <style> HTML-комментарии тоже не работают, так как в CSS код комментируется другим способом, о котором вы узнаете в части «Знакомство с CSS».

Чтобы быстро закомментировать или раскомментировать строку кода в HTML или CSS редакторе, можете использовать сочетание клавиш ctrl + / или cmd + /.

Добавить комментарий