ScreenshotNeo

BlogHow-to

How to Prettify HTML, CSS, and JavaScript

Use Prettier to format HTML, CSS, and JavaScript consistently, with practical CLI, editor, browser, and troubleshooting guidance.

By the ScreenshotNeo team1 October 20266 min read

Use Prettier when you want one consistent formatter for HTML, CSS, and JavaScript. Prettier parses your files and prints them in a consistent style instead of preserving the original layout. Its official documentation lists support for JavaScript, CSS, Less, SCSS, and HTML: Prettier documentation.

For most projects, install Prettier locally, run it from your package scripts or editor, review the diff, then enforce it in continuous integration. The examples below show a complete setup, file-specific commands, configuration, browser-only formatting, alternatives, and fixes for common failures.

1. Install Prettier in a project

From the project directory:

npm install --save-dev --save-exact prettier

Create a test file and run a check without changing files:

npx prettier . --check

Format supported files in place:

npx prettier . --write

Use explicit globs when you want to limit the operation:

npx prettier '**/*.{html,css,scss,less,js,jsx,mjs,cjs}' --write

2. Format each language

JavaScript

npx prettier src/app.js --write
npx prettier src/app.js --check

Prettier normally selects the JavaScript parser from the .js extension. You can select one explicitly when formatting stdin or an unusual filename:

printf 'const answer={meaning:42};\n' | npx prettier --parser babel

CSS, SCSS, and Less

npx prettier styles/main.css --write
npx prettier styles/theme.scss --write
npx prettier styles/legacy.less --write

Prettier keeps CSS syntax valid while normalizing spacing, indentation, selector layout, and declaration wrapping.

HTML

npx prettier public/index.html --write

HTML can contain whitespace that affects rendering. Review changes involving text nodes, inline elements, navigation links, and email templates before committing.

3. Add project scripts

Add predictable commands to package.json:

{
  "scripts": {
    "format": "prettier . --write",
    "format:check": "prettier . --check"
  }
}

Run them with:

npm run format
npm run format:check

Use format:check in CI so a pull request fails when committed files do not match the project style.

4. Configure output deliberately

Prettier is opinionated, but a small configuration file can set the project-wide choices that matter:

{
  "semi": true,
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "trailingComma": "all",
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "css"
}

Save this as .prettierrc (JSON), or use another supported configuration format. Keep the file in version control so editors and CI use the same settings.

The HTML option htmlWhitespaceSensitivity has three documented modes: css, strict, and ignore. Choose deliberately and inspect rendered output when whitespace between inline elements matters. See the Prettier options reference.

5. Exclude generated and vendor files

Create a .prettierignore file for content that should not be reformatted:

node_modules
coverage
dist
build
public/vendor
*.min.js
*.min.css

Do not ignore source files merely because they are inconvenient to format. Generated output, third-party bundles, and minified assets are the usual exclusions.

6. Format from JavaScript code

You can call Prettier’s Node API from a script when formatting is part of a build or migration:

import fs from 'node:fs/promises';
import prettier from 'prettier';

const file = 'src/app.js';
const source = await fs.readFile(file, 'utf8');
const options = await prettier.resolveConfig(file);
const formatted = await prettier.format(source, {
  ...options,
  filepath: file
});
await fs.writeFile(file, formatted);

Passing filepath lets Prettier infer the parser from the filename and apply project configuration.

7. Format code in an editor

  1. Install the official Prettier extension for your editor.
  2. Set Prettier as the default formatter for JavaScript, CSS, and HTML.
  3. Enable format on save only after checking the project configuration.
  4. Run npm run format:check before committing.

Editor integrations make formatting immediate, while the repository script remains the source of truth for every contributor and CI runner.

8. Browser-only formatting

Prettier provides a standalone browser build. The browser documentation states that this version does not depend on Node.js. It requires the parser and plugins you intend to use, and it does not support configuration files, ignore files, CLI usage, or automatic plugin loading. Read the browser documentation for the standalone build and plugin setup.

Use browser formatting for an in-browser editor or a one-off tool. For a repository, the CLI or editor integration is safer because it can load project configuration and ignore rules.

9. Prettier versus js-beautify

Question Prettier js-beautify
Primary goal One consistent, opinionated style Dedicated formatters with more layout controls
Languages JavaScript, CSS-family files, HTML, and more Separate JavaScript, CSS, and HTML commands
Layout control Fewer style decisions More indentation and wrapping controls
Embedded code Parses supported embedded languages Documents JavaScript and CSS inside HTML
Best fit Teams seeking a shared baseline Projects needing manual presentation control

The js-beautify package documentation describes its separate formatters and configuration controls. Compare both tools on language coverage, embedded-code handling, editor and CLI integration, and how much style control your project needs.

10. Review formatting safely

  • Run the formatter on a branch or a focused commit.
  • Inspect the diff, especially HTML text nodes and templates.
  • Open representative pages and check whitespace-sensitive layouts.
  • Keep formatting-only changes separate from behavior changes.
  • Commit the configuration and ignore files with the baseline.

11. Troubleshooting

Symptom Cause Fix
“No parser could be inferred” The file has an unusual or missing extension. Rename it or pass --parser babel, --parser css, or --parser html.
CI says files are unformatted Local and CI Prettier versions or configs differ. Pin the version with --save-exact, commit config files, and use prettier --check.
HTML layout changes after formatting Whitespace between inline elements is significant. Review the diff and choose htmlWhitespaceSensitivity deliberately.
Vendor files changed The files are not ignored. Add generated or third-party paths to .prettierignore.
Editor and CLI disagree The editor is using a global formatter or a different working directory. Select the project-local Prettier installation and verify the loaded config.
Formatting fails on valid-looking code The source is not parseable for the selected language. Fix syntax errors first; formatters cannot reliably print invalid input.
Browser build cannot format a language The required parser or plugin was not loaded. Load the standalone parser and corresponding plugin explicitly; browser mode does not auto-load plugins.

12. Performance, reliability, and cost

Formatting is usually fastest and most reliable when Prettier runs locally from the pinned project dependency. Format only changed files in pre-commit hooks, and run a full --check in CI. Avoid formatting minified bundles and generated directories because they create noisy diffs and waste work. Prettier is a development dependency; its cost is the compute time of your local machine or CI runner.

Or skip the browser setup

If your goal is to capture the formatted page rather than build a browser automation stack, ScreenshotNeo returns a screenshot or PDF from one GET request. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

See the ScreenshotNeo API documentation for all options.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also provides an MCP server for Claude, Cursor, and other MCP clients, plus full-page capture, element selectors, custom CSS and JavaScript, device presets, PDFs, caching, signed links, async jobs, bulk capture, and a usage API. A free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create your free ScreenshotNeo account.

FAQ

Should I format before or after minifying?

Format source files before minification. Keep minified output out of normal formatting runs.

Does Prettier change program behavior?

It is intended to preserve semantics, but HTML whitespace can affect rendering. Review diffs and test whitespace-sensitive templates.

Can I use Prettier without Node.js?

Yes. The standalone browser build does not depend on Node.js, but it requires explicit parsers and plugins and lacks project config and ignore-file support.

How do I enforce one style across a team?

Pin Prettier in devDependencies, commit the configuration, add a format script, and run prettier --check in CI.