Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overhaul code example guidelines #28017

Merged
merged 5 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Guidelines for styling CSS code examples
title: Guidelines for writing CSS code examples
slug: MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/CSS
page-type: mdn-writing-guide
---
Expand All @@ -10,6 +10,14 @@ The following guidelines cover how to write CSS example code for MDN Web Docs.

## General guidelines for CSS code examples

### Choosing a format

Opinions on correct indentation, whitespace, and line lengths have always been controversial. Discussions on these topics are a distraction from creating and maintaining content.

On MDN Web Docs, we use [Prettier](https://prettier.io/) as a code formatter to keep the code style consistent (and to avoid off-topic discussions). You can consult our [configuration file](https://github.com/mdn/content/blob/main/.prettierrc.json) to learn about the current rules, and read the [Prettier documentation](https://prettier.io/docs/en/index.html).

Prettier formats all the code and keeps the style consistent. Nevertheless, there are a few additional rules that you need to follow.

### Plan your CSS

Before diving in and writing huge chunks of CSS, plan your styles carefully. What general styles are going to be needed, what different layouts do you need to create, what specific overrides need to be created, and are they reusable? Above all, you need to try to **avoid too much overriding**. If you keep finding yourself writing styles and then cancelling them again a few rules down, you probably need to rethink your strategy.
Expand All @@ -26,7 +34,7 @@ Don't use preprocessor syntax, such as [Sass](https://sass-lang.com/), [Less](ht

In the same spirit as the previous guideline, don't write example codes on MDN Web Docs using a specific CSS methodology such as [BEM](http://getbem.com/naming/) or [SMACSS](http://smacss.com/). Even though they are valid CSS syntax, the naming conventions can be confusing to people not familiar with those methodologies.

### Don't use resets <!--is this valid in current times-->
### Don't use resets

For maximum control over CSS across platforms, a lot of people used to use CSS resets to remove every style, before then building things back up themselves. This certainly has its merits, but especially in the modern world, CSS resets can be an overkill, resulting in a lot of extra time spent reimplementing things that weren't completely broken in the first place, like default margins, list styles, etc.

Expand Down Expand Up @@ -154,61 +162,6 @@ In a stylesheet that contains [media query](/en-US/docs/Web/CSS/CSS_media_querie
}
```

- When a rule has multiple selectors, put each selector on a new line. This makes the selector list easier to read and can help to make code lines shorter.

Do this:

```css example-good
h1,
h2,
h3 {
font-family: sans-serif;
text-align: center;
}
```

Not this: <!--I thought this is the preferred style-->

```css-nolint example-bad
h1, h2, h3 {
font-family: sans-serif;
text-align: center;
}
```

## Space after function parameters

Function parameters should have spaces after their separating commas, but not before:

```css example-good
color: rgb(255, 0, 0);
background-image: linear-gradient(to bottom, red, black);
```

## Syntax style

There are a variety of CSS writing styles you can use, but we prefer the expanded style, with the selector/opening brace, close brace, and each declaration on a separate line. This maximizes readability, and again, promotes consistency on MDN Web Docs.

In addition, keep these specifics in mind:

- Include a space between the selector(s) and the opening curly brace.
- Always include a semicolon at the end of the last declaration, even though it isn't strictly necessary.
- Put the closing curly brace on a new line.
- In each declaration, put a space after the separating colon, but not before.
- Use two spaces for code indentation.

```css example-good
p {
color: white;
background-color: black;
padding: 1rem;
}
```

```css-nolint example-bad
p { color: white; background-color: black; padding: 1rem; }
```

## Value to turn off properties

When turning off borders (and any other properties that can take `0` or `none` as values), use `0` rather than `none`:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Guidelines for styling HTML code examples
title: Guidelines for writing HTML code examples
slug: MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/HTML
page-type: mdn-writing-guide
---
Expand Down Expand Up @@ -78,16 +78,16 @@ Omitting quotes can also cause problems. In the above example, the `alt` attribu

## Boolean attributes

Don't write out boolean attributes in full; you can just write the attribute name to set it. For example, you can write:
Don't include values for boolean attributes (but do include values for {{glossary("enumerated")}} attributes); you can just write the attribute name to set it. For example, you can write:

```html example-good
required
<input required />
```

This is perfectly understandable and works fine; the longer version with the value is supported but not necessary:
This is perfectly understandable and works fine. If a boolean HTML attribute is present, the value is true. While including a value will work, it is not necessary and incorrect:

```html-nolint example-bad
required="required"
```html example-bad
<input required="required" />
```

## Case
Expand All @@ -114,18 +114,6 @@ Use semantic class/ID names, and separate multiple words with hyphens. Don't use
<p class="bigRedBox">Blah blah blah</p>
```

## Double quotes

Use double quotes for HTML, not single quotes, like so:

```html example-good
<p class="important">Yes</p>
```

```html-nolint example-bad
<p class='important'>Nope</p>
```

## Entity references

Don't use entity references unnecessarily — use the literal character wherever possible (you'll still need to escape characters like angle brackets and quote marks).
Expand All @@ -142,8 +130,6 @@ Instead of:
<p>&copy; 2018 Me</p>
```

This is fine as long as you declare a UTF-8 character set.

## HTML elements

There are some rules for writing about HTML elements on MDN Web Docs. Adhering to these rules produces consistent descriptions of elements and their components and also ensures correct linking to detailed documentation.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Guidelines for styling code examples
title: Guidelines for writing code examples
slug: MDN/Writing_guidelines/Writing_style_guide/Code_style_guide
page-type: mdn-writing-guide
---
Expand Down Expand Up @@ -42,38 +42,21 @@ Some more general best practices include:

## Guidelines for formatting

These guidelines for formatting code examples for MDN Web Docs are also good practices when you are coding.
Opinions on correct indentation, whitespace, and line lengths have always been controversial. Discussions on these topics are a distraction from creating and maintaining content.

### Indentation
On MDN Web Docs, we use [Prettier](https://prettier.io/) as a code formatter to keep the code style consistent (and to avoid off-topic discussions). You can consult our [configuration file](https://github.com/mdn/content/blob/main/.prettierrc.json) to learn about the current rules, and read the [Prettier documentation](https://prettier.io/docs/en/index.html).

- Use two spaces per tab for indentation in all code examples.
- Place the open-brace ("`{`") characters on the same line as the statement that opens the block.
Prettier formats all the code and keeps the style consistent. Nevertheless, there are a few additional rules that you need to follow.

```html example-good
<div>
<p>This is my paragraph.</p>
</div>
```
These MDN Web Docs guidelines for formatting code examples are also good practices when you are coding.

```js example-good
function myFunc() {
if (thingy) {
console.log("Yup, that worked.");
}
}
```
### Choosing a syntax language

### Spacing
To ensure proper formatting and syntax highlighting of code blocks, writers must specify the language of the code block they are writing in. See [Example code blocks in MDN Markdown](/en-us/docs/MDN/Writing_guidelines/Howto/Markdown_in_MDN#Example_code_blocks) for a list of languages supported by MDN, as well as details on how to request a new language.

Add a space between a control statement or loop keyword and its opening parenthesis.
If the code block is pseudo-code, the output of a command, or otherwise not a programming language, explicitly set the language to `plain`.

```js example-good
if (condition) {
/* handle the condition */
} else {
/* handle the "else" case */
}
```
> **Warning:** if the desired language is not yet supported by MDN, do **not** set the language of a code block to a similar language, as doing so may have unintended side effects with Prettier formatting and syntax highlighting.

### Code line length

Expand Down Expand Up @@ -124,15 +107,13 @@ const toolkitProfileService = Components.classes[

### Code block height

Code blocks should be as long as they need to be, but no longer. Ideally, aim for something short like 15-25 lines. If a code block is going to be a lot longer, consider just showing the most useful snippet, and link to the full example on a GitHub repo or codepen, say. <!--is this the current recommendation?-->
Code blocks should be as long as they need to be, but no longer. Ideally, aim for something short, like 15-25 lines. If a code block is going to be a lot longer, consider just showing the most useful snippet, and link to the complete example on a GitHub repo or CodePen, say.

#### Inline code formatting

Use the {{HTMLElement("code")}} tags to mark up function names, variable names, and method names.
For example: "the `frenchText()` function".
Use inline code syntax (\`) to mark up function names, variable names, and method names. For example: "the `frenchText()` function".

**Method names should be followed by a pair of parentheses.** For example, `doSomethingUseful()`.
The parentheses help differentiate methods from other code terms.
**Method names should be followed by a pair of parentheses**: for example, `doSomethingUseful()`. The parentheses help differentiate methods from other code terms.

## Guidelines for proper rendering

Expand Down Expand Up @@ -160,18 +141,18 @@ These guidelines should be followed to ensure that the code examples you write d
color: rgb(248, 242, 230);
```

- If you have to use hex colors, then use lower-case:
- For hex colors, use the short form where relevant:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i disagree with this one.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This guideline has been around for a long time; I didn't add it. :P


```css example-good
color: #058ed9;
color: #a39a92;
color: #a39a92c1;
color: #ff0;
queengooborg marked this conversation as resolved.
Show resolved Hide resolved
color: #fbfa;
```

- Use the short form where relevant:

```css example-good
color: #ff0;
color: #fff;
```css-nolint example-bad
color: #ffff00;
color: #ffbbffaa;
```

### Mark rendered examples as good or bad
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Guidelines for styling JavaScript code examples
title: Guidelines for writing JavaScript code examples
slug: MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/JavaScript
page-type: mdn-writing-guide
---
Expand All @@ -24,10 +24,6 @@ Prettier formats all the code and keeps the style consistent. Nevertheless, ther

You can use new features once every major browser — Chrome, Edge, Firefox, and Safari — supports them.

### Spacing and indentation

Mark indentation with _2 spaces_. Don't use the tab character. The end-of-line character is `\n`, the Unix convention. To help you, we have included an [`.editorconfig`](https://editorconfig.org/) file in the repository. Many editors read its content and use it to configure their behavior.

## Arrays

### Array creation
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
---
title: Guidelines for styling shell prompt code examples
title: Guidelines for writing shell prompt code examples
slug: MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/Shell
page-type: mdn-writing-guide
---

{{MDNSidebar}}

A shell is a program that waits for you to type in a command and then press the return key. To indicate which commands you should type, content on MDN Web Docs lists them in a code block, similar to code examples. Such a block looks like this:
The following guidelines cover how to write Shell prompt code examples for MDN Web Docs.

## What is a "shell"

A shell is a program that waits for you to type in a command and then press the return key. To indicate which commands you should type, content on MDN Web Docs lists them in a code block, similar to code examples.

Such a block looks like this:

```bash example-good
# This may take a while...
hg clone https://hg.mozilla.org/mozilla-central/ firefox
cd firefox
git clone https://github.com/mdn/content
cd content
```

The following guidelines cover how to write Shell prompt code examples for MDN Web Docs.
## General guidelines for shell prompt code examples

### Choosing a format

Opinions on correct indentation, whitespace, and line lengths have always been controversial. Discussions on these topics are a distraction from creating and maintaining content.

On MDN Web Docs, we use [Prettier](https://prettier.io/) as a code formatter to keep the code style consistent (and to avoid off-topic discussions). You can consult our [configuration file](https://github.com/mdn/content/blob/main/.prettierrc.json) to learn about the current rules, and read the [Prettier documentation](https://prettier.io/docs/en/index.html).

Prettier formats all the code and keeps the style consistent. Nevertheless, there are a few additional rules that you need to follow.

## General guidelines for shell prompt examples
### Writing shell code blocks

When writing a shell code block:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ The following checklist is good to keep in mind while writing and reviewing cont
- **Review page structure**: Review the page to ensure that it's structured properly for the [type of page](/en-US/docs/MDN/Writing_guidelines/Page_structures/Page_types) it is <!--link to be revised-->. Be sure every section that it should have is present and has appropriate content.
- **Ensure completeness**: Review sections to ensure that no information is missing. Ensure that all parameters are listed and explained. Ensure that any exceptions are covered — this is a particularly common place where content is missing.
- **Ensure all concepts are fully fleshed-out**: It's easy to give a quick explanation of something, but make sure that all the nuances are covered. Are there special cases? Are there any known restrictions that the reader might need to know about?
- **Add examples**: There should be examples covering all parameters or at least the parameters (or properties, or attributes) that users from the beginner-through-intermediate range are likely to use, as well as any advanced ones that require extra explanation. Each example should be preceded with an overview of what the example will do, what additional knowledge might be needed to understand it, and so forth. After the example (or interspersed among pieces of the example) should be text explaining how the code works. Don't skimp on the details and the handling of errors in examples. Keep in mind that users _will_ copy and paste your example to use in their own projects, and your code _will_ wind up used on production sites! See our [code example guidelines](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide) for more useful information. <!--link to be revised-->
- **Add examples**: There should be examples covering all parameters or at least the parameters (or properties, or attributes) that users from the beginner-through-intermediate range are likely to use, as well as any advanced ones that require extra explanation. Each example should be preceded with an overview of what the example will do, what additional knowledge might be needed to understand it, and so forth. After the example (or interspersed among pieces of the example) should be text explaining how the code works. Don't skimp on the details or the handling of errors in examples. Keep in mind that users _will_ copy and paste your example to use in their own projects, and your code _will_ wind up used on production sites! See our [code example guidelines](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide) for more useful information.
- **Explain use cases**: If there are particularly common use cases for the feature being described, talk about them! Instead of assuming that a user will figure out that the method being documented can be used to solve a common development problem, actually add a section about that use case with an example and text explaining how the example works.
- **Add image information**: Include proper [`alt`](/en-US/docs/Web/HTML/Element/img#alt) text on all images and diagrams. This text, as well as captions on tables and other figures, counts because spiders can't crawl images, and so `alt` text tells search engine crawlers what content the embedded media contains.
> **Note:** It is not recommended to include too many keywords or keywords not related to the feature in an attempt to manipulate search engine rankings; this type of behavior is easy to spot and tends to be penalized.
Expand Down Expand Up @@ -415,7 +415,7 @@ A page on MDN Web Docs can contain more than one code example. The following lis
- If you are working with a large piece of example code, it may make sense to break it up into smaller logical parts so that they can be described individually.
- When adding [live samples](/en-US/docs/MDN/Writing_guidelines/Page_structures/Live_samples) <!--link to be revised-->, it's helpful to be aware that all of the {{HTMLElement("pre")}} blocks in the area that contains the sample are concatenated together before running the example, which lets you break any or all of the HTML, CSS, and JavaScript into multiple segments, each optionally with its own descriptions, headings, and so forth. This makes documenting code incredibly powerful and flexible.

To learn about how to style or format code examples for MDN Web Docs, see [Guidelines for styling code examples](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide). <!--link to be revised-->
To learn about how to style or format code examples for MDN Web Docs, see [Guidelines for styling code examples](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide).

### External links

Expand Down