How To Set Up Your HTML Project With VS Code
To explore HTML in practice and begin building an HTML website, we’ll need to set up a new project using a text editor. This tutorial series uses Visual Studio Code, a free code editor available for Mac, Windows, or Linux, but you may use whichever code editor you prefer.
After opening your preferred text editor, open up a new project folder and name it html-practice . We’ll use this folder to store all the files and folders we create in the course of this tutorial series.
To create a new project folder in Visual Studio Code, navigate to the “File” menu item in the top menu and select “Add Folder to Workspace.” In the new window, click the “New Folder” button and create a new folder called html-practice as illustrated in the gif below:
Next, create a new file called index.html inside the html-practice folder. We’ll use this file through the tutorial series to experiment with HTML. If you are using Visual Studio Code, you can create a new file by using Right Click (on Windows) or CTRL + Left Click (on Mac) on the html-practice folder, selecting “New File”, and creating the file index.html as illustrated in the gif below:
You now have a project folder and file for exploring HTML. We’ll return to this file in the tutorials ahead.
Debugging and Troubleshooting CSS and HTML
Before we get started with our HTML exercises, be aware that precision is important when writing HTML. Even an extra space or mistyped character can keep your code from working as expected.
If your HTML code is not rendering in the browser as intended, make sure you have written the code exactly. To troubleshoot errors, check for extra or missing spaces, missing or misspelled tags, and missing or incorrect punctuation or characters. Each time you change your code, make sure to save your file before reloading it in the browser to check your results.
A Quick Note on Automatic HTML Support Features
Some code editors—such as the Visual Studio Code editor that we’re using in this series—provide automatic support for writing HTML code. For Visual Studio Code, that support includes smart suggestions and auto completions. While this support is often useful, be aware that you might generate extra code that will create errors if you’re not used to working with these support features. If you find these features distracting, you can turn them off in the code editor’s preferences.
We are now ready to begin learning how the CSS language works. In the next tutorial, we’ll begin exploring how CSS rules are used to control the style and layout of HTML content on a webpage.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Build a Website with HTML
This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior coding experience is necessary but we recommend you start at the beginning of the series if you wish to recreate the demonstration website.
At the end of this series, you should have a website ready to deploy to the cloud and a basic familiarity with HTML. Knowing how to write HTML will provide a strong foundation for learning additional front-end web development skills, such as CSS and JavaScript.
HTML in Visual Studio Code
Visual Studio Code provides basic support for HTML programming out of the box. There is syntax highlighting, smart completions with IntelliSense, and customizable formatting. VS Code also includes great Emmet support.
IntelliSense
As you type in HTML, we offer suggestions via HTML IntelliSense. In the image below, you can see a suggested HTML element closure </div> as well as a context specific list of suggested elements.

Document symbols are also available for HTML, allowing you to quickly navigate to DOM nodes by id and class name.
You can also work with embedded CSS and JavaScript. However, note that script and style includes from other files are not followed, the language support only looks at the content of the HTML file.
You can trigger suggestions at any time by pressing ⌃Space (Windows, Linux Ctrl+Space ) .
You can also control which built-in code completion providers are active. Override these in your user or workspace settings if you prefer not to see the corresponding suggestions.
Close tags
Tag elements are automatically closed when > of the opening tag is typed.
The matching closing tag is inserted when / of the closing tag is entered.
You can turn off autoclosing tags with the following setting:
Auto update tags
When modifying a tag, the linked editing feature automatically updates the matching closing tag. The feature is optional and can be enabled by setting:
Color picker
The VS Code color picker UI is now available in HTML style sections.

It supports configuration of hue, saturation and opacity for the color that is picked up from the editor. It also provides the ability to trigger between different color modes by clicking on the color string at the top of the picker. The picker appears on a hover when you are over a color definition.
Hover
Move the mouse over HTML tags or embedded styles and JavaScript to get more information on the symbol under the cursor.

Validation
The HTML language support performs validation on all embedded JavaScript and CSS.
You can turn that validation off with the following settings:
Folding
You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Folding regions are available for all HTML elements for multiline comments in the source code.
Additionally you can use the following region markers to define a folding region: <!— #region —> and <!— endregion —>
If you prefer to switch to indentation based folding for HTML use:
Formatting
To improve the formatting of your HTML source code, you can use the Format Document command ⇧⌥F (Windows Shift+Alt+F , Linux Ctrl+Shift+I ) to format the entire file or Format Selection ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F ) to just format the selected text.
The HTML formatter is based on js-beautify. The formatting options offered by that library are surfaced in the VS Code settings:
- html.format.wrapLineLength : Maximum amount of characters per line.
- html.format.unformatted : List of tags that shouldn’t be reformatted.
- html.format.contentUnformatted : List of tags, comma separated, where the content shouldn’t be reformatted.
- html.format.extraLiners : List of tags that should have an extra newline before them.
- html.format.preserveNewLines : Whether existing line breaks before elements should be preserved.
- html.format.maxPreserveNewLines : Maximum number of line breaks to be preserved in one chunk.
- html.format.indentInnerHtml : Indent <head> and <body> sections.
- html.format.wrapAttributes : Wrapping strategy for attributes:
- auto : Wrap when the line length is exceeded
- force : Wrap all attributes, except first
- force-aligned : Wrap all attributes, except first, and align attributes
- force-expand-multiline : Wrap all attributes
- aligned-multiple : Wrap when line length is exceeded, align attributes vertically
- preserve : Preserve wrapping of attributes
- preserve-aligned : Preserve wrapping of attributes but align
Tip: The formatter doesn’t format the tags listed in the html.format.unformatted and html.format.contentUnformatted settings. Embedded JavaScript is formatted unless ‘script’ tags are excluded.
The Marketplace has several alternative formatters to choose from. If you want to use a different formatter, define "html.format.enable": false in your settings to turn off the built-in formatter.
Emmet snippets
VS Code supports Emmet snippet expansion. Emmet abbreviations are listed along with other suggestions and snippets in the editor auto-completion list.
Tip: See the HTML section of the Emmet cheat sheet for valid abbreviations.
If you’d like to use HTML Emmet abbreviations with other languages, you can associate one of the Emmet modes (such as css , html ) with other languages with the emmet.includeLanguages setting. The setting takes a language identifier and associates it with the language ID of an Emmet supported mode.
For example, to use Emmet HTML abbreviations inside JavaScript:
HTML custom data
You can extend VS Code’s HTML support through a declarative custom data format. By setting html.customData to a list of JSON files following the custom data format, you can enhance VS Code’s understanding of new HTML tags, attributes and attribute values. VS Code will then offer language support such as completion & hover information for the provided tags, attributes and attribute values.
You can read more about using custom data in the vscode-custom-data repository.
HTML extensions
Install an extension to add more functionality. Go to the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and type ‘html’ to see a list of relevant extensions to help with creating and editing HTML.
Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
Next steps
Read on to find out about:
-
— VS Code has first class support for CSS including Less and SCSS. — Learn about VS Code’s powerful built-in Emmet support. — Emmet, the essential toolkit for web-developers.
Common questions
Does VS Code have HTML preview?
No, VS Code doesn’t have built-in support for HTML preview but there are extensions available in the VS Code Marketplace. Open the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) and search on ‘live preview’ or ‘html preview’ to see a list of available HTML preview extensions.
Настройка VSCode для работы с HTML
В прошлых статьях ( первая часть , вторая часть ) мы рассмотрели установку среды разработки VSCode под Windows 10 и добавили в неё поддержку языка C++.
VSCode является универсальной IDE, благодаря наличию онлайн каталога с множеством расширений, позволяющих настроить среду как вам удобней. При этом её можно использовать для разработки на разных языках программирования.
Данная среда может использоваться и для разработки HTML-страниц.
Сегодня мы рассмотрим установку двух расширений Browser Preview и Live Server, которые позволяют создавать HTML-сайты не устанавливая отдельный web-сервер, и производить отладку и правку дизайна сайта не переключаясь между редактором и браузером!
Установка расширения Browser Preview
чтобы открыть окно Расширения.
Нам потребуется установить расширения Browser Preview от автора Kenneth Auchenberg.

Данное расширение позволяет вам организовывать просмотр страницы непосредственно в IDE, что очень полезно, при внесении в HTML-страницу множества мелких правок.
Также нам понадобится расширение – Live Server от Ritwick Dey.
Установка расширения Live Server
Это по сути небольшой web-сервер не требующий долгой настройки и готовый к запуску по одному щелчку на кнопку!

После установки Live Server обязательно закройте VSCode и запустите его снова.
Установка
Возможно, вам так же придется установить расширение Debugger for Chrome от Microsoft.
Создание проекта
Давайте создадим тестовый проект для нашей страницы.
Допустим, все проекты у нас будут храниться в папке d:\html
Откроем консоль cmd.exe и введем команды:
Откроется новое окно VSCode, в котором уже открыта папка проекта test1:

Добавим в нее новый файл index.html
Для этого нажмите на указанную кнопку и введите имя файла:

Щелкните на файл, чтобы открыть его в редакторе.
Давайте создадим простейшую страницу:
Проверка HTML-страницы
У нас есть проект и web-страница, пришло время её проверить.
Сначала запустим Live Server, для этого просто нажмите кнопку Go Live:

Откроется новое окно браузера и сервер будет запущен на порту

Закройте вкладку браузера, мы будем использовать Browser Preview
Создание конфигурации для запуска Browser Preview
Выберите меню Run -> Add configuration…

Выберите пункт Browser Preview
Будет создан файл launch.json замените его содержимое на:
Сохраните и закройте вкладку.
Запустите Browser Preview, для этого нажмите F5 или на указанную кнопку, она появится после первого запуска конфигурации:


.
Нажмите на «Запустить test1…»
Откроется вкладка с нашей страницей:

Работа с Browser Preview
Данное расширение очень удобно при разработке страниц с нуля, так как позволяет видеть изменения сразу после сохранения страницы.
Давайте добавим текст на страницу:
Нажмите Ctrl+S – страница будет сохранена и тут же обновиться вкладка с нашим сайтом в Browser Preview

Отладка сайта в браузере
Вы можете использовать внешний браузер для отладки сайта, запущенного в Live Server
Запустите Google Chrome и откройте в нем ссылку http://localhost:5500
Я расположил окна рядом, для большей наглядности.
Давайте добавим еще одну строку в html-файл:
Сохраним файл – содержимое обновится и в браузере, и во вкладке Browser Preview.

Заключение
Сегодня мы рассмотрели настройку среды разработки VSCode для разработки HTML-страниц.
Мы установили расширения Browser Preview и Live Server.
Создали тестовую страницу.
Настроили профиль для запуска нашей страницы в Browser Preview.
Открыли нашу страницу во вкладке Browser Preview и протестировали автоматическое обновление содержимого вкладки при обновлении содержимого HTML-страницы.
Открыли нашу страницу в Google Chrome используя ссылку от Live Server — http://localhost:5500
Протестировали обновление страницы в Google Chrome при обновлении содержимого файла.
В следующей статье мы рассмотрим настройку VSCode для разработки на языке программирования PHP.
How To Easily Write HTML5 Boilerplate Code In Visual Studio Code
Visual Studio Code is a very popular IDE among web developers. If you are a web developer, you need to fill below code every time a new file is created.
We do not have to write again and again in Visual Studio Code. There is a shortcut to add above content easily to a HTML file.
HTML5 Shortcut
To try the shortcut, create a new HTML file in Visual Studio Code. Then, start typing html .

From the intellisense dropdown, select html:5 and press Enter key. Visual Studio automatically brings the boilerplate HTML5 code to the file.
The shortcuts like html:5 are called Emmet Abbreviation. If you are working with some libraries like React, and you wish to have a shortcut to create a component, you can search for React emmet plugins in VS Code. It is available. ES7+ React/Redux/React-Native snippets is one such extension.