zaro

How to Auto Format HTML in VSCode

Published in VSCode HTML Formatting 3 mins read

To auto-format HTML files in Visual Studio Code, you typically install a dedicated formatting extension like Prettier, then configure it to work with your project.

Here's a breakdown based on a common setup process:

Steps to Set Up Auto-Formatting for HTML

Setting up automatic HTML formatting in VSCode usually involves these key steps, often guided by a popular formatting extension:

  1. Install the Extension: First, you need to add a formatter extension to your VSCode installation. Prettier is a widely used choice for this purpose. You can find it in the VSCode Extensions Marketplace by searching for "Prettier".
  2. Open Your Project: Navigate to and open the project containing your HTML files within Visual Studio Code.
  3. Run the Setup Command: Access the Command Palette in VSCode by pressing Ctrl+Shift+P (or Cmd+Shift+P on macOS). Type a command like "Set Auto Formatting" or look for commands related to the formatter you installed (e.g., "Prettier: Create configuration file").
  4. Configure Settings: The extension often guides you through setting up configuration files (like .prettierrc) and updates your VS Code settings (settings.json) to make the formatting automatic, potentially on save.

Note: The specific command in step 3 might vary slightly depending on the exact extension used, but the purpose is to integrate the formatter with your project and VS Code settings.

Common Auto-Formatting Settings

Once the extension is set up, you might adjust VSCode's built-in settings to ensure formatting happens automatically.

Here are some relevant settings you can configure in settings.json:

  • editor.defaultFormatter: Set this to the ID of your chosen formatter (e.g., "esbenp.prettier-vscode" for Prettier) for HTML and other supported languages.
  • editor.formatOnSave: Enable this (true) to automatically format the file every time you save it.
  • editor.formatOnPaste: Enable this (true) if you want pasted content to be automatically formatted.

Example settings.json snippet:

"[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
}

This tells VSCode to use Prettier as the default formatter specifically for HTML files and to format them automatically on save.

Summary of Steps

Step Action How to Do It
Install Add formatter extension (e.g., Prettier) VSCode Extensions Marketplace
Open Project Load your project folder File > Open Folder...
Run Setup Execute extension's setup command Command Palette (Ctrl+Shift+P)
Configure (Optional) Adjust VSCode settings.json for auto-save formatting File > Preferences > Settings

By following these steps, you can ensure your HTML code is consistently formatted according to predefined rules, improving readability and maintaining code style across your project.