Guidelines for styling code examples - The MDN project .

Html Coding



This section provides the best practices for creating an understandable minimal code example to demonstrate the usage of a specific feature or function.

Code examples that you add to MDN Web Docs should be:

  • simple enough to be understandable, but
  • complex enough to do something interesting, and preferably useful.

There is one overarching consideration that you need to keep in mind: Readers will copy and paste the code sample into their own code and may put it into production.

Therefore, you should make sure that the code example is usable, follows generally accepted best practices, and does not do anything that will cause an application to be insecure, grossly inefficient, bloated, or inaccessible. If the code example is not runnable or production-worthy, be sure to include a warning in a code comment and in the explanatory text; for example, if it is only a snippet and not a full example, make this clear. This also means that you should provide all of the information necessary to run the example including any dependencies and setup information.

Code examples should be as self-contained and easy to understand as possible. The aim is not necessarily to produce efficient, clever code that impresses experts and has great functionality, but rather to produce reduced working examples that can be understood as quickly as possible.

Some more general best practices include:

  • The code example should be short and ideally show only the feature you are immediately interested in.
  • Only include code that is essential for the example. A large amount of non-relevant code can easily distract or confuse the reader. If you want to provide a full, more lengthy example, put it in one of our GitHub repos (or a JSBin, Codepen, or similar) and then provide the link to the full version above or below the sample.
  • Don't include unnecessary server-side code, libraries, frameworks, preprocessors, and other such dependencies. They make the code less portable and harder to run and understand. Use vanilla code where possible.
  • Don't assume readers' knowledge of any libraries, frameworks, preprocessors, or other non-native features. For example, use class names that make sense within the example rather than class names that make sense to BEM or Bootstrap users.
  • Write your code to be as clean and understandable as possible, even if it is not the most efficient way to write it.
  • Don't use bad practices for brevity (such as presentation elements like <big> or document.write()); do it correctly.
  • In the case of API demos, if you are using multiple APIs together, point out which APIs are included and which features come from where.