HTML, CSS & JavaScript

While there are a phenomenal amount of resources available on the Internet, we have compiled a concise tutorial on how to code (modern) HTML and CSS, to be used as an easy reference while you work on your pages. The final section on JavaScript only shows how to incorporate it into your pages, and further chapters will have many more examples.

These three technologies are used on the client-side (in the browser, after being retrieved from the server). Everything else we discuss in Reporting is server-side (generating content to be sent to the client).

This is also an easy resource to use to copy-and-paste snippets into your own pages, though more useful examples will appear in later chapters.

HTML

HTML stands for HyperText Markup Language and is a text format for creating documents meant for display in web browsers. For HTML's history and an alternative description of the format, here is a link to Wikipedia: en.wikipedia.org/wiki/HTML. The official HTML specification is here: html.spec.whatwg.org

Syntax

A Markup Language is a text format that defines elements in a document by using tags. Each element is defined by an opening tag, followed by the element's content, and terminated by a closing tag. The content may be text and/or more (nested) elements. Tags are never seen by the reader of the document; only the content of each element is.

A tag starts with a less-than sign <, immediately followed by the tag's name, and ends with a greater-than sign >. Most tags also require an end tag after the element's content and (potentially) inner (nested) tags. The closing tag has a solidus (forward slash) / immediately after the < followed by the opening tag's name. Spaces are allowed inside a tag, but only after its name. Tag names are case-insensitive.

Here is an example of the paragraph tag, which has the tag name p and encapsulates the text of a paragraph in the document: <p>Lorem ipsum dolor sit amet</p>

The opening tag can also contain “attributes”. For example, here the “style” attribute is set to “background-color:#FFFF00”, which is CSS for giving the whole paragraph a yellow background: <p style="background-color:#FFFF00">Lorem ipsum dolor sit amet</p>

The web browser will display the words between the tags, appropriately spaced from a previous paragraph, and with the colour and other characteristics defined by the tag's attributes. The tags themselves are invisible to the reader:

Lorem ipsum dolor sit amet

Document structure

Here is an example of a minimal HTML document:

<!DOCTYPE html>
<html>
  <head>
    <title>This is a title</title>
  </head>
  <body>
    <p>Hello world!</p>
  </body>
</html>
The HTML5 identifier

<!DOCTYPE html> tells browsers that the HTML5 format (the most modern version as of 2023) will be used. All HTML documents should have this as the first line. It is conventional (but not necessary) to write !DOCTYPE in uppercase but all other tag codes and attributes in lowercase.

Document structure elements
  • <html>..</html> is the root element of an HTML document. All other elements are contained by this element. You should therefore have </html> as the very last tag in the document.
  • <head>..</head> is a container for processing information and metadata and a good place to place CSS and JavaScript that will be used by the body of the document.
  • <body>..</body> is a container for all visible content of the document.

Attributes

HTML attributes define the characteristics of the tag. Multiple attributes are separated by spaces.

Most attributes are in the form attribute=value and it is conventional to quote the value part with double quotes, though strictly only necessary if the value contains spaces or characters that are not letters, digits, the hyphen, or the period. Single quotes may also be used. [ref]

Boolean attributes have no value. For example, the presence of the “checked” attribute determines whether a checkbox starts out in the checked state (): <input type="checkbox" checked> (Strictly speaking, this form is shorthand for <input type="checkbox" checked="checked">.)

Common attributes

The most common attributes, applicable to nearly all HTML elements, are:

  • id - unique identifier for the element that allows it to be located by JavaScript for inspection or alteration as well as be the target of an in-page link with an #id in the URL; it does not need to be a number and can be any string of text.
  • class - the name of a CSS class that will determine the element's visual characteristics.
  • style - in-line CSS style description; use sparingly, but it has its place.

Character references

Because the < and > characters have a special purpose in HTML (to define tags), they cannot be used normally in text. Instead, these characters need to be replaced by character references (also called entity references or HTML entities). A character reference starts with an ampersand &, followed by a short (case-sensitive) code and ends with a semi-colon ; without any spaces. Because of this, the usage of the ampersand may be ambiguous, and, unless the ampersand is followed by a space, it should be replaced by the character reference for it. There are many named character references (listed here: html.spec.whatwg.org/multipage/named-characters.html) but most are simply for convenience when using UTF-8 (see below). The entities that you will use mostly when hand-coding HTML are:

  • &lt; for <
  • &gt; for >
  • &amp; for &
  • &nbsp; for non-breaking space
  • &mdash; for the Em-dash:

Character references can also use numbers (Unicode code points) to insert any conceivable character (with a few exceptions like the NUL and other control characters). There are two forms of numeric character references: decimal, e.g. &#163; for £ and hexadecimal, e.g. &#xA3; also for the pound sign. If you use the pound sign often, it is easier to remember its named reference, &pound;. Since HTML in Planet must be in UTF-8 encoding, you can also simply copy-and-paste such characters from other documents.

A useful character that doesn't have a named reference is:

  • &#x202F; (hexadecimal variant) &#8239; (decimal variant) for a narrow non-breaking space, which is great to use as thousand-separators in a long number, e.g.: 9 007 199 254 740 991

UTF-8

The default character set for HTML5 is UTF-8. This is a character set that coincides with the ASCII character set for the first 127 code points and thereafter uses a variable number of bytes to encode larger code points. This makes it the most compact text encoding for the English language, resulting in smaller documents for most content on the Internet. The use of UTF-8 also makes all entities, except the three listed above, unnecessary. (UTF-8 was not in use during the early days of the World Wide Web.) For more on UTF-8, see Wikipedia here: en.wikipedia.org/wiki/UTF-8

Importantly, PlanetGIS forces the content of HTML to be encoded in UTF-8. While it is possible to specify different character encodings for HTML, e.g. UTF-16, do not do this for PlanetGIS pages. It is good practice (though unnecessary) to specify the character set in the <head> section. If you want to do that, it must be: <meta charset="utf-8">

Whitespace & line breaks

In HTML, line breaks and repeated spaces are ignored in the final presentation of the document. A line break in the HTML code (meaning that the next character starts on a new line in the source code after pressing ) does not tell the browser to start the next word on a new line. For example, the following HTML code:

<p>
word1   word2

word3   word4
</p>
produces:

word1 word2 word3 word4

The repeated spaces, the line breaks after the <p> tag, and subsequent lines have no effect on the final presentation. Paragraphs are automatically spaced apart according to the document's (or the browser's default) style sheet (CSS) as are other elements like headings.

Non-breaking space

A single space tells the browser to either provide an offset (as defined by the designer of the current font) between words or break the line of text (start the next word on a new line) if there is no more usable area to the right for the next word.

In order to force extra horizontal whitespace, you need to use the character reference: &nbsp; Use this sparingly, and if you find yourself repeating it, you likely need to look to CSS for padding and margins. The actual function of &nbsp; is to prevent a line break between words (move the line break to an earlier opportunity), for example, in cases where breaking words would be undesirable, like 100 km/h or 12 pm.

Hard line breaks

Use the break tag: <br> to force a line break inside a paragraph. A repeated break tag will create empty lines of text (extra horizontal whitespace); however, this is again an indication that you need to look to CSS to define margins for the element.

In the above example, to get the desired visual presentation, the HTML would be:

<p>
word1&nbsp;&nbsp;&nbsp;word2<br>
<br>
word3&nbsp;&nbsp;&nbsp;word4<br>
</p>
which produces:

word1   word2

word3   word4
HTML (source code) formatting

The use of line breaks inside and outside of paragraph tags (and anywhere else, with few exceptions) is purely a preference of the HTML coder, who might feel that the HTML source is more readable with spacing. The same goes for indentation, which makes it easier to visually pair opening and closing tags when they have the same amount of preceding spaces (or tabs) for indentation, as you've seen in the above hello world example of a complete HTML document. (The tab character is another whitespace character that has no effect on the final presentation of HTML.)

It is better to keep the text of a paragraph to lines of no more than 80 to 120 characters to make editing the HTML source code easier. Line breaks in the source code mean one thing only: The next character is the start of a new word. There is one exception: the <pre> tag, which is used in this documentation for multi-line code examples. The <pre> tag preserves spaces used for indentation, does not need <br> at the end of each line, and is styled in CSS to use a monospace font.

Comments

To remove a part of the document from all processing and display, a “comment” tag can be used. The comment tag looks like this:
<!-- A comment -->
In this form, it is useful for placing notes in the document that will not be seen by the reader of the document but may be helpful to future editors of the document.

Another form is to eliminate entire sections of the document from processing, presumably temporarily, in case the section will be required at a later stage. For example, <!-- <p>A paragraph</p> --> removes the paragraph element (and potential other nested elements) from the document for purposes of processing and display (everything inside is ignored).

Paragraphs

As already seen in the examples above, each paragraph should be encapsulated in <p>...</p> tags. Text outside of paragraph tags will be displayed without preceding and following vertical space. Inside a paragraph, use the <br> tag to start text on a new line and repeat to create blank lines with the height of the current font.

Lists

Lists can replace paragraphs in cases where each paragraph should be preceded by a bullet or a number.

Bullet lists

To create a bullet list, encapsulate the list in <ul>...</ul> tags and each list item in <li>...</li> tags (ul is for an unordered list):

<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>

Which produces:

  • List item 1
  • List item 2
  • List item 3
Numbered lists

To create a numbered list, encapsulate the list in <ol>...</ol> tags and each list item in <li>...</li> tags (ol is for ordered list):

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

Which produces:

  1. List item 1
  2. List item 2
  3. List item 3

The bullet style and numbering system can be customised with CSS.

Headings

HTML defines 6 levels of headings. The highest level heading is encapsulated in a <h1> tag:

<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>

This is rendered (using this document's style sheet) as follows:

Heading level 1

Heading level 2

Heading level 3

Heading level 4

Heading level 5
Heading level 6

Links

To create a link (or hyperlink) in an HTML document, use the anchor tag with the destination URL as the href attribute and put the text you want to be hyperlinked before the closing tag:

<a href="https://docs.planetgis.org">PlanetGIS Documentation</a>

produces:

PlanetGIS Documentation

The appearance of the link (text colour and whether it is underlined) is defined in CSS.

Absolute vs relative links

Relative links should be used to target pages in the same project (database, website). A relative link does not have parts 1-3 shown in the previous chapter (the scheme and server address) in the href attribute. Relative links keep working when your pages are moved to another domain (server address) or when the same pages are used on different servers (e.g. your localhost web server in addition to a regular web server in your data centre).

Web browsers automatically combine relative URLs in links with the URL of the current page. For example, a link in the page at https://docs.planetgis.org/Index that looks like this: Chapter?Id=710181492479568300 will replace the Index portion to become https://docs.planetgis.org/Chapter?Id=710181492479568300

If a relative URL starts with a / it is still relative in the sense that it refers to a page in the same site, but absolute within the project (web site) because it defines the full path of the target. If a part of the target page's path is renamed, e.g. a page with path /Report/MyReport is renamed to /Reports/MyReport, all links to the MyReport page that included the full path (starting with / will be broken (point to a non-existing page). Planet allows the renaming of directories, which are really just partial renames of the group contained by a directory node. (Pages in Planet do not reside in directories/folders; each has a full path for its name and they are only shown in a typical folder structure similar to your file system.)

A fully relative link does not start with a /, but is either just the name of a page (meaning the target has the same path up to the last / as the source) or starts with ../ which means up one level or, stated differently, delete the part of the source's path between the second-last and last /, then add the target link withough the ../). ../ may be repeated as necessary, e.g., ../../, means two levels up in the hierarchy and the relative link may include further directory levels, e.g. ../NewReports/Report.

If the pages are in different branches all the way up to the root, it is usually better to use the site-absolute option (full path, starting with /). However, if a target is expected to keep its position relative to the source, fully relative links are better. Consider the following structure:

  1. /Final/Reports/Index - a page containing a list of reports (and links to them)
  2. /Final/Reports/Report1 - a page that contains a link to Report2
  3. /Final/OldReports/Report2 - a page that contains a link to Report1
  4. /Draft/Reports/Report3
  • A link in the Index page (1) targeting Report1 (2) should look like this: Report1
  • A link in the Index page (1) targeting Report2 (3) should look like this: ../OldReports/Report2
  • A link in the Report2 page (3) targeting Report1 (2) should look like this: ../Reports/Report2
  • A link in the Report3 page (4) targeting Report1 (2) could look like this: ../../Reports/Report2 or /Final/Reports/Report2 depending on which variant you feel is safer when considering future changes to the structure.

In the above example, the Reports and OldReports directories can be moved, together, to another directory (or the Final directory renamed) without affecting the links between pages but in the fourth case, only if the first variant was used.

Absolute links must start with https:// (or http://) to tell the browser not to combine the URL with the current page's URL. A link that looks like this href="www.google.com" is not absolute, even if it may look that way. In summary:

  • Fully relative: ../Index or Chapter?Id=710181492479568300
  • Relative, but site-absolute: /Index
  • Absolute: https://docs.planetgis.org/Index
The advantage of the relative option is that entire sub-hierarchies will retain the correct links between pages within the sub-hierarchy, where site-absolute links will fail. Site-absolute links are safer when the target is expected to be in a more stable location (changes unlikely) but the source is likely to be moved or renamed. For example, any URLs to images in /Art of this web site should be site-absolute.

Opening links in new tabs

A regular link takes the browser to a new page in place of the current page. Sometimes it is desirable that the browser opens a new tab for the link so that the current page remains open. (In general, you should only do this for external links, i.e. to other websites.) Use the target attribute with a value of _blank to accomplish this:

<a href="https://en.wikipedia.org" target="_blank">en.wikipedia.org<a>

produces:

en.wikipedia.org

and will open in a new tab.

The convention in this documentation is to show the URL to the user in the case of important external links, in case the documentation will be printed on paper. This should not be done mid-sentence, as it would break the flow of the sentence. (Important links should be placed at the end of a sentence).

Link titles

The title attribute provides a mouse-over tip explaining the purpose of the link. For example:

<a href="https://en.wikipedia.org" target="_blank" title="A link to Wikipedia">en.wikipedia.org</a>

produces (place your mouse cursor over the link and pause it for a second):

en.wikipedia.org
In-page links

An anchor in a URL (the text after a #) tells the browser to look for an element (usually a heading or section) with an id attribute that matches the text (case-sensitively). For example, if a page contains <h1 id="anchorname"> or <section id="anchorname">, then the following link will cause the browser to jump to that element:

<a href="/path/to/page#anchorname">link text</a>

To jump to locations on the same page, use a URL that starts with a #, followed by the anchor.

This is what the link looks like that takes you to the section on URLs in the previous chapter:

<a href="Chapter?Id=710181492479568300#713630226660135681">here</a>

The highighted part is the value of the id attribute of a <section> in that page, separated from the rest of the URL by a #.

Download links

Browsers normally make assumptions about whether to display or download the content of a link, based on the content-type header that the server sends with the content. To force, for example, an image to be downloaded to the user's computer (and stay on the current page), you can add the download attribute:

<a href="/Art/Logo78.png" download>Download our logo</a>

Without the download attribute, the browser will replace the entire page with the image. Here is the above link, if you want to test it:

Download our logo

You can also specify a file name as the value of the download attribute. This is very useful when making download links to PlanetGIS' attachments (BLOBs). Attachments (and their thumbnails) are referenced by their AttachmentId, which means there is no file name that can be derived from the link, unlike in the above example where the downloaded file will be Logo78.png. Without specifying a file name, the name of the downloaded file will just be a number with no extension (e.g. .png), so will not look like a normal file in Windows Explorer and you will not be able to double-click on it to launch the default application for it:

<a href="/Attachment/710587087714313124" download="Producing PDFs.png">Download an attachment</a>
Download an attachment

Images

To insert an image into an HTML document, use the <img> tag. This is one of the few HTML tags that does not have a closing </tag>.

The src attribute provides the URL to the image. For example, this site's logo looks as follows in HTML:

<img src="/Art/Logo78.png">

To scale the image to a desired size, use the width attribute. The height attribute helps the browser determine the document's layout before the image has been loaded, but you need to keep it at the same ratio as the original image to avoid having it stretched out of proportion. For this reason, the height is often omitted.

<img src="/Art/Logo78.png" width="100" height="100">

Here you see the effect of an incorrect height attribute. The values for width and height do not have to be quoted, as in this example, but it is conventional to quote all attribute values, since technically they are strings.

Lazy loading

If your page is likely going to require scrolling in order to reach the bottom, it is strongly advised to use lazy loading for all images other than those at the top of your page:

<img src="/Art/Logo78.png" loading="lazy">

Images are usually orders of magnitude larger to transfer than the HTML content of a page. By doing this, you delay the download of images that may never be needed, thus saving bandwidth in addition to reducing the time to load the page.

High resolution displays

Cellphones and high-end computer monitors have much higher pixel densities than standard computer monitors. On such displays, web browsers have to scale images so that an image pixel takes up more than one screen pixel in order for the page to look similar in proportion to the page rendered on a regular monitor. If you provide higher-resolution images for such displays, your pages will look much better. To do that, use the srcset attribute in place of src.

The srcset attribute accepts a comma-separated list of URLs with a space separating each URL's pixel density indicator. For example, our logo at the top-left actually has the following HTML:

<img srcset="Art/Logo52.png 1x, Art/Logo65.png 1.25x, Art/Logo78.png 1.5x">

The browser will download only one of the images, choosing the best image for the display's pixel density:

Your browser chose ?. (This information was obtained by using JavaScript after the page loaded on your device.) If you are using a high-resolution display (that is, your browser chose Logo78.png), you will notice that the image above is scaled smaller than the first example. This is because in the first example, the browser did not know that the image was made for a higher pixel density, and therefore scaled it larger, as it needs to do with any other regular image in order for the page to look similar in proportion to the page rendered on a regular monitor.

Floating - wrapping text around your images

This paragraph is wrapped around the logo image, which is floated left. In-line CSS is used to do this by setting the style attribute to float: left; margin-right: 0.5em, though separate CSS classes could also be created for a left and right floating image. margin-right: 0.5em specifies half an M's width of spacing (minimum) between the text and the image. See below for more on CSS.

Styling text

Spans of text, i.e. words or phrases, can be given distinctive appearances by enclosing them in special HTML tags. There is also a semantic aspect to this, where providing meaning is the main purpose and visual style specified elsewhere (in a centralised location). This is partly due to accessibility concerns, mostly to do with screen readers for blind people, but in general, the emphasis on meaning also allows computers to better understand documents on the Web.

It is also important to realise that the visual appearance of tags can be redefined in any way, while the meaning of the tags is clearly defined. Well, in most cases.

Bold text

The stylistic versus semantic tags to create bold text are the most similar in practice, but in theory and as dictated by the HTML5 specification:

  • <b>..</b> — a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede. [ref]
  • <strong>..</strong>
    • Importance: used in a heading, caption, or paragraph to distinguish the part that really matters from other parts that might be more detailed, more jovial, or merely boilerplate.
    • Seriousness: used for a warning or cautionary notice.
    • Urgency: used to denote contents that the user needs to see sooner than other parts of the document. [ref]
Italicised and emphasised text

The distinction here is much clearer. According to the HTML5 specification:

  • <i>..</i> — a span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, transliteration, a thought, or a ship name in Western texts. [ref]
  • <em>..</em> — provides stress emphasis to its contents, which screen readers will clearly convey by means of a tonal change. [ref]
Underlining and highligting text
  • <u>..</u> — the HTML5 specification is somewhat convoluted here[ref], but the gist is that the need for underlining text should be rare considering other options that are available, for example (in addition to the above),
  • <mark>..</mark> — a background colour change (normally) for a span of text for reference purposes, due to its relevance in another context. [ref]
  • Strikethrough text
  • <s>..</s> — a span of text that is no longer accurate or relevant. [ref].
  • <del>..</del> — a span of text that has been removed or perhaps will be permanently removed in future. [ref]
  • Quotation marks

    In technical documents like this one, quotation marks are used relatively rarely to indicate speech by a person or another author. Blockquote paragraphs are better suited to content from another source. It is a style convention to choose quotation marks over, for example, italicization to introduce a new term because italicization is used for so many other purposes, including important ones like emphasis.

    There is no clear semantic use defined in the HTML specification[ref]. In these pages, we often use quotation marks to introduce a technical term or wording that would otherwise be peculiar in plain English text. In other words, we use quotation marks where English words have been reappropriated for describing a technical concept that has little to do with the original meaning of the words. The semantic use is: we, or others, refer to this concept by these words (though here we were obviously using quotes to indicate speech!)

    Another example is the quoting of accessibility at the start of this section, where the quotes imply that the meaning of the word in this context is specific (referring to considerations for visually impaired people), as will be explained or has been explained elsewhere. Note also that when repeating the word or phrase in the same section, it is better to do so without quotation marks, implying that the specific meaning is now understood by the reader.

    We also use <q>..</q> for convenience:

    • Left and right double quotation marks look much nicer than regular " but it is cumbersome to enter the character codes or copy them from elsewhere, since they are not on a keyboard.
    • Nested quotes automatically get single (left and right) quotation marks, e.g. double quotes with nested single quotes (<q>double quotes with nested <q>single quotes</q></q>)
    Superscript and subscript
    • Superscript: <sup>..</sup> — used in mathematical and scientific typography e.g. E = mc2, a reference to a nearby note or an external reference link[ref].
    • Subscript: <sub>..</sub> — scientific topography e.g. H2O, variable numbers e.g. X0, etc.
    Small print

    <small>..</small> can be used for fine print but should not be used for entire paragraphs. Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or to satisfy licencing requirements. [ref]

    The reason <small> has not been deprecated in HTML5, like <big>, is that it has semantic value, meaning fine print. (Big print is covered, semantically, by HTML headers.).

    CSS

    CSS stands for Cascading Style Sheets and its purpose is to describe the presentation (i.e. fonts, colours, and layout) of HTML documents. Modern HTML should have no —or as little as possible— style descriptions embedded in it. Rather, elements in an HTML document should be matched to styles described in a separate style sheet.

    By separating CSS (normally into a .css file) from HTML, it becomes much easier to change the appearance of a document, and the same content can be used in a multitude of themes and layouts. It is also easier to maintain by focusing exclusively either on structure and content, or style, and this can be done by different people with different strengths. A single .css file can be used to provide all the styling information for an entire website consisting of thousands of pages.

    Linking, embedding & inlining

    Linking

    To use a CSS file in an HTML document, place the following inside the <head> section of the HTML:
    <link rel="stylesheet" href="/path/to/stylesheet.css">

    To serve this file from Planet's web server, create a page with CSS content type and place the CSS content in the CSS tab.

    Embedding

    When an HTML document is required to have a very specific or unique style, and perhaps future modifications to its style is undesirable (for example a report that should remain unaltered after publication), the CSS should be embedded in the <head> section of the HTML, which still makes coding and maintaining the <body> section of the document easier.

    To embed CSS in an HTML document, place the CSS content inside <style>..</style> tags nested in the <head> section.

    Inlining

    HTML elements can also have CSS inlined in the style attribute of a tag. The value of the style attribute will be a string (in quotes) containing one or more ; separated declarations, as would otherwise be in a declaration block in a style sheet. (The {..} must not appear in inlined CSS, only the declarations.) For example, the following creates a span of red text: <span style="color:red">red text</span>.

    Applying style in this manner should be rare. In the above example, we really only wanted the text to be red, so it is acceptable. However, the text is likely red only because of some meaning attached to it, e.g. very important, in which case it is better to create a CSS class .importanttext { color:red } elsewhere, so that it can later be changed in one place (to also make it bold, for example). It is very useful for initial states of HTML elements, for example to hide an element until the user does something: <p id="hiddenparagraph" style="display: none">This paragraph will initially be hidden.</p>

    Syntax

    A style sheet consists of a list of rules. Each rule has one or more selectors followed by a declaration block that starts with a { and ends with a }. The declaration block contains a list of declarations in the form property: value; Here is an example of a rule in a style sheet:

    aside {
      width: 30%;
      padding: 1rem;
      margin: 0 0 1rem 1rem;
      float: right;
    }
    

    This is for <aside> elements in these pages, setting them up to use 30% of available width (in section paragraph space), padded so that content is surrounded by 1 font width unit of the aside element's background and offset by the same amount from paragraph text to the left and below.

    Selectors

    Selectors determine which HTML elements the declaration block applies to, by matching tag codes and attributes. Selectors can apply to the following:

    • All elements of a specified type, e.g. a level 1 header <h1>, for which the selector is the element name: h1
    • An element selected by matching its id attribute (which should be unique in the document), for which the selector starts with a #, similar to a URL anchor e.g. #identifier
    • All elements with the specified class attribute, for which the selector starts with a ., e.g. .classname
    • All elements of a specified type that also has the specified class, for which the selector is the element name followed by the class selector, e.g. h1.red
    • All elements (the universal selector), which is *

    Class names and id values are case sensitive, and should not contain spaces or start with numbers. Hyphens - and underscores _ are acceptable in any position, as are any characters outside the ASCII range (Unicode code points greater than 127), but class names and ids should not contain other special characters in the ASCII range like $.

    Declaration block

    The declaration block, which starts with a { and ends with a }, contains a semicolon ; separated list of declarations, each of which is a property: values pair. The property name is followed by a : and values are separated by spaces. Whitespace (space and newlines) are not important in any way other than to separate values or selectors, but consistent use of spacing and indentation greatly improves readabilty. Before the next property (declaration) - after all values - a ; is required. The last declaration (before the block's closing }) does not require a ;, but it is better to place one at the end of the values regardless, so it won't be forgotten when another declaration is added later.

    Selector grouping & combinators

    Grouping

    Selectors can be grouped if their declarations are identical, to avoid repetition. To combine selectors with the same declarations, list them separated by a ,, e.g. the following sets the same bottom margin (spacing to paragraphs) for headings of all levels:

    h1, h2, h3, h4, h5, h6 {
      margin-bottom: 0.5rem;
    }

    Further rules can specify properties that have different values, e.g. font size, for each heading level separately. This is one aspect of cascading described below.

    Combinators

    A CSS selector can be specific about the relationship between two selectors. There are four types of relationships that can be specified:

    • Decendant - matched elements must be descendants of (inside) elements matched by the first selector: p a (space between selectors) selects links only if they are inside paragraph elements, but also if nested deeper inside (e.g. a span element).
    • Child - matched elements must be immediate descendants of (inside, but not nested deeper) elements matched by the first selector: body>h1 (> between selectors) selects level 1 headings only if they are directly inside the body of the document (at the top level).
    • General sibling - matched elements must have the same parent as elements matched by the first selector: h2~p (~ between selectors) selects all paragraphs that follow a level 2 heading; the heading and all paragraphs must have the same parent (be directly inside the same element and not nested deeper).
    • Adjacent sibling - matched elements must follow directly after elements matched by the first selector: h2+p (+ between selectors) selects only the first paragraph after a level 2 heading, i.e. the paragraph starts directly after the closing tag of the h2 element </h2>

    Cascading

    Multiple style sheets will be merged to produce a final style sheet. Web browsers start with a default style sheet and each style sheet you link, embed or inline is merged with that. You can therefore have a style sheet that is applicable to all your pages and more specific style sheets (perhaps embedded in the HTML) for each page. When the selector indicates multiple hits of style sheet declarations for an element, properties of the same name will have their values replaced in order of priority and unspecified properties will inherit the value from the prior declaration. For example, for red text:

    1. The browser's default style sheet is used first: body { font-size: 1rem; color: black; }
    2. The linked style sheet of this document specifies a larger font size: body { font-size: 1.125rem; }
    3. The inlined style attribute changes the text colour to red: <span style="color: red">red text</span>

    In the same style sheet, the last declaration block takes priority over earlier ones. The specificity, media type and !important keyword affects the priority further, as will be explained below.

    Specificity

    Units

    The most common distance units in CSS are as follows.

    rem

    Root Em — the width of the letter M using the browser's default font. 1rem is usually 16px but can be changed in the browser's Settings page. This is the best unit to use that is relative only to the user's overall preference of font size, as set in the user's browser and operating system.

    em

    1em is the width of the letter M in the current font selected for an element. A similar unit, ch is the width of a 0 in the current font. This unit is ideal for padding and margins, taking into consideration the current element's font size.

    px

    1px is one pixel on a low-dpi (standard) computer monitor and is defined as 1/96th of an inch, or about 1/4mm. The font scaling of your operating system affects the actual size of 1px. On a 4K monitor, you likely have 150% scaling as seen in the figure below, which would make the size of 1px equal ~0.4mm (or 1/64th of an inch). On a cellphone display, the scaling is typically much more.

    Operating system scale setting
    %

    For width or height units, 100% is the inner width or height of the parent element.

    vw and vh

    1vw is 1% of the inside width of the browser window. 1vh is 1% of the inside height of the browser window.

    You can also use the minimum and maximum values of the browser window's inner dimensions. 1vmin is 1% of either the width or height, chosing the lesser value. 1vmax is 1% of either the width or height, chosing the greater value.

    pt, pc, cm, mm, in

    These units are absolute measurement values that are only appropriate when printing. You can set up stylesheet rules specifically for printing and use these units. Do not use these units for layouts on a computer screen. The browser really has no idea what these units mean (can only guess), unless you are printing. A pt (point) is used to specify font size in typesetting and is defined to be 1/72nd of an inch. 1pc (pica) is 12pt.

    Colours

    Colour values can be specified in a number of ways:

    • keyword — one of 140 colour names, listed here: www.w3.org/TR/css-color-3/#svg-color
    • hexadecimal RGB# followed by three or six hexadecimal digits. The 3 digit version expands to the 6 digit version by doubling each digit in order to produce white (#FFFFFF) from #FFF.
    • rgb(red, green, blue) — each colour component is a value between 0 and 255, e.g. rgb(255, 0, 0) is red.
    • rgba(red, green, blue, alpha) — the fourth component is transparency and ranges from 0.0 (fully transparent) to 1.0 (fully opaque).
    • hsl(hue, saturation, lightness)
      • hue is a degree on the colour wheel with 0 red, 120 green 240 blue.
      • saturation is a percentage value with 0% meaning gray and 100% fully saturated colour.
      • lightness is a percentage with 0% meaning black and 100% white.
    • hsla(hue, saturation, lightness, alpha) — the fourth component is transparency and ranges from 0.0 (fully transparent) to 1.0 (fully opaque).

    Properties and their values

    font
    • font-size: valid values are any of the above distance units or one of the following keywords: xx-small, x-small, small, medium, large, x-large, xx-large, xxx-large, where medium corresponds to the browser's default font size, i.e. 1rem. Two more keywords adjust the font size relative to the element's parent: smaller and larger
    • font-family: a comma-separated list of names of alternate fonts, from highest priority to lowest. The first font that is found on the browser's operating system that contains the needed glyphs will be chosen. Always provide one of the generic font family names as the last option in the list: serif, sans-serif, monospace, cursive and fantasy.
    • font-style: one of the following keywords: normal, italic, oblique. italic selects a font that is classified as such and oblique algorithmically slants a font. You can also specify the slant in degrees, e.g. oblique 14deg. 14deg is the default if you omit the slant specification.
    • font-weight: one of the following values or keywords: 100, 200, 300, 400/normal, 500, 600, 700/bold, 800, 900. You can also increase or decrease font weight relative to the parent element's font weight with lighter and bolder.
    • line-height: the keyword normal (which is usually equivalent to around 1.2), a number that is multiplied to the font's height, or a percentage that works the same.

    A shorthand form combines all or some of the above in a set order. A few examples:

    • font-size font-family — font: 1.2em "Times New Roman", serif;
    • font-size/line-height font-family — font: 1.2em/2 "Times New Roman", serif;
    • font-style font-weight font-size font-family — font: italic bold 1.2em "Times New Roman", serif;
    margin

    The margin is the empty area around an element separating it from neighbouring elements. Each of the four sides can be specified separately, each with a distance unit, or just 0:

    • margin-top: 1em;
    • margin-right: 5%;
    • margin-bottom: 2px;
    • margin-left: 0;

    A shorthand form combines the values as follows:

    • One value: same margin on all four sides.
    • Two values: first value is top and bottom, second value left and right.
    • Three values: first value is the top, second value left and right, third value bottom.
    • Four values: values are clockwise in the following order: top, right, bottom, left.

    The keyword auto can be used to centre the element within its parent. margin: 0 auto; centres an element horizontally.

    padding

    Padding is the area inside an element's boundary, limiting the space available to contained elements. Padding values are exactly as margin values (above).

    border

    An element's border is the area between its margin and its padding, in other words the rectangular shape that defines the extent of an element.

    • border-style: one of the following keywords: none, hidden, solid, dotted, dashed, double. Each of the four sides can be specified separately:
      • border-top-style: solid;
      • border-right-style: dotted;
      • border-bottom-style: dashed;
      • border-left-style: none;
      or with the shorthand form: border-style: solid dotted dashed none; following the same order and combinations as with margins.
    • border-width: one of the following keywords: thin, medium, thick (exact width may vary among browsers) or a distance unit. Each of the four sides can be specified separately:
      • border-top-width: 1px;
      • border-right-width: 0.5em;
      • border-bottom-width: medium;
      • border-left-width: 0;
      or with the shorthand form: border-width: 1px 0.5em medium 0; following the same order and combinations as with margins.
    • border-color: the colour of each of the four sides can be specified separately:
      • border-top-color: red;
      • border-right-color: #FF0000;
      • border-bottom-color: rgb(255, 0, 0);
      • border-left-color: hsl(0, 100%, 50%);
      or with the shorthand form: border-color: red; following the same order and combinations as with margins.
    • border-radius: a single distance unit that specifies the rounding radius.

    There is a shorthand form for specifying the values for all sides, e.g. border: 2px solid red; or the values can be specified per side:

    • border-top: 1px solid black;
    • border-right: 0.1em dotted blue;
    • border-bottom: 2px dashed rgb(0, 255, 0);
    • border-left: 3px double #FFFF00;

    JavaScript

    JavaScript is a programming language that runs in web browsers and is very useful for programmatic control over HTML elements. JavaScript can be embedded in HTML, or - like CSS - be linked in the <head> section and then used as if it was embedded.

    Here is an example of a JavaScript program that will change an HTML element in this document:

    <script>
    function myScript()
    {
      let target=document.getElementById('myscripttarget');
      target.innerHTML='This paragraph\'s text <mark>has now changed because you clicked on the button!</mark>';
    }
    </script>
    

    This paragraph's text will change when you click this button:

    Linking, embedding & inlining

    All three methods below can be used in the same document, each one repeatedly.

    Linking

    To use a JavaScript file in an HTML document, place the following inside the <head> section of the HTML:
    <script src="/path/to/javascript.js">

    To serve this file from Planet's web server, create a page with JavaScript content type and place the JavaScript content in the JavaScript tab.

    Embedding

    If your JavaScript only applies to one HTML document it is best to place the JavaScript content inside <script>..</script> tags nested in the <head> section. It is also valid to put <script>..</script> tags anywhere in the <body> section.

    Inlining

    Most HTML elements have event properties that will execute JavaScript inlined in the value string of the event attribute. It is best to use this to call a JavaScript function located elsewhere in a <script> tag, and not place a little program in the attribute value.

    The above JavaScript example uses the following HTML and inline JavaScript for the button: <input type="button" value="Click me!" onclick="myScript()">