What is a web server? - Learn web development

What is a web server?
=====================

In this article, we explain what web servers are, how web servers work, and why they are important.

|  |  |
| --- | --- |
| Prerequisites: |
 You should already know
 how the Internet works, and
 understand the difference between a web page, a website, a web
server, and a search engine.
  |
| Objective: |
 You will learn what a web server is and gain a general understanding of
 how it works.
  |

Summary
-------

The term *web server* can refer to hardware or software, or both of them working together.

1. On the hardware side, a web server is a computer that stores web server software and a website's component files (for example, HTML documents, images, CSS stylesheets, and JavaScript files). A web server connects to the Internet and supports physical data interchange with other devices connected to the web.
2. On the software side, a web server includes several parts that control how web users access hosted files. At a minimum, this is an *HTTP server*. An HTTP server is software that understands URLs (web addresses) and HTTP (the protocol your browser uses to view webpages). An HTTP server can be accessed through the domain names of the websites it stores, and it delivers the content of these hosted websites to the end user's device.

At the most basic level, whenever a browser needs a file that is hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct (hardware) web server, the (software) *HTTP server* accepts the request, finds the requested document, and sends it back to the browser, also through HTTP. (If the server doesn't find the requested document, it returns a 404 response instead.)

![Basic representation of a client/server connection through HTTP](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_web_server/web-server.svg)

To publish a website, you need either a static or a dynamic web server.

A **static web server**, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files as-is to your browser.

A **dynamic web server** consists of a static web server plus extra software, most commonly an *application server* and a *database*. We call it "dynamic" because the application server updates the hosted files before sending content to your browser via the HTTP server.

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with content from a database. Sites like MDN or Wikipedia have thousands of webpages. Typically, these kinds of sites are composed of only a few HTML templates and a giant database, rather than thousands of static HTML documents. This setup makes it easier to maintain and deliver the content.

Deeper dive
-----------

To review: to fetch a webpage, your browser sends a request to the web server, which searches for the requested file in its own storage space. Upon finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

### Hosting files

First, a web server has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and video.

Technically, you could host all those files on your own computer, but it's far more convenient to store files all on a dedicated web server because:

* A dedicated web server is typically more available (up and running).
* Excluding downtime and system troubles, a dedicated web server is always connected to the Internet.
* A dedicated web server can have the same IP address all the time. This is known as a *dedicated IP address*. (Not all ISPs provide a fixed IP address for home lines.)
* A dedicated web server is typically maintained by a third party.

For all these reasons, finding a good hosting provider is a key part of building your website. Examine the various services companies offer. Choose one that fits your needs and budget. (Services range from free to thousands of dollars per month.) You can find more details in this article.

Once you have web hosting service, you must upload your files to your web server.

### Communicating through HTTP

Second, a web server provides support for HTTP (**H**yper**t**ext **T**ransfer **P**rotocol). As its name implies, HTTP specifies how to transfer hypertext (linked web documents) between two computers.

A Protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

Textual

All commands are plain-text and human-readable.

Stateless

Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server can't remember a password you typed or remember your progress on an incomplete transaction. You need an application server for tasks like that. (We'll cover that sort of technology in other articles.)

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later. For now, just be aware of these things:

* Usually only *clients* make HTTP requests, and only to *servers*. Servers *respond* to a *client*'s HTTP request. A server can also populate data into a client cache, in advance of it being requested, through a mechanism called server push.
* When requesting a file via HTTP, clients must provide the file's URL.
* The web server *must answer* every HTTP request, at least with an error message.

On a web server, the HTTP server is responsible for processing and answering incoming requests.

1. Upon receiving a request, an HTTP server checks if the requested URL matches an existing file.
2. If so, the web server sends the file content back to the browser. If not, the server will check if it should generate a file dynamically for the request (see Static vs. dynamic content).
3. If neither of these options are possible, the web server returns an error message to the browser, most commonly `404 Not Found`.
 The 404 error is so common that some web designers devote considerable time and effort to designing 404 error pages.
 ![The MDN 404 page as an example of such error page](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_web_server/mdn-404.jpg)
### Static vs. dynamic content

Roughly speaking, a server can serve either static or dynamic content. Remember that the term *static* means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

The term *dynamic* means that the server processes the content or even generates it on the fly from a database. This approach provides more flexibility, but the technical stack is more complex, making it dramatically more challenging to build a website.

It is impossible to suggest a single off-the-shelf application server that will be the right solution for every possible use case. Some application servers are designed to host and manage blogs, wikis, or e-commerce solutions, while others are more generic. If you're building a dynamic website, take the time to research your requirements and find the technology that best fits your needs.

 Most website developers won't need to create an application server from scratch, because there are so many off-the-shelf solutions, many of which are highly configurable.
 But if you do need to create your own server, then you will probably want to use a server framework, leveraging its existing code and libraries, and extending just the parts that you need in order to meet your use case.
 Only a relatively small number of developers should need to develop a server completely from scratch: for example, in order to meet tight resource constraints on an embedded system.
 If you'd like to experiment with building a server, take a look through the resources in the Server-side website programming learning pathway.

Next steps
----------

Now that you are familiar with web servers, you could:

* read up on how much it costs to do something on the web
* learn more about various software you need to create a website
* move on to something practical like how to upload files on a web server.


What is the difference between webpage, website, web server, and search engine? - Learn web development

What is the difference between webpage, website, web server, and search engine?
===============================================================================

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

|  |  |
| --- | --- |
| Prerequisites: |
 You should know
 how the Internet works.
  |
| Objective: |
 Be able to describe the differences between a web page, a website, a web
 server, and a search engine.
  |

Summary
-------

As with any area of knowledge, the web comes with a lot of jargon. Don't worry. We won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset since you'll hear these expressions all the time as you read on. It's easy to mix these terms since they refer to related but different functionalities. You'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable.

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

web page

A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Edge, or Apple Safari. These are also often called just "pages."

website

A collection of web pages which are grouped together and usually connected together in various ways. Often called a "website" or a "site."

web server

A computer that hosts a website on the Internet.

search engine

A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

1. Find a search index and look for the title of the book you want.
2. Make a note of the catalog number of the book.
3. Go to the particular section containing the book, find the right catalog number, and get the book.

Let's compare the library with a web server:

* The library is like a web server. It has several sections, which is similar to a web server hosting multiple websites.
* The different sections (science, math, history, etc.) in the library are like websites. Each section is like a unique website (two sections do not contain the same books).
* The books in each section are like webpages. One website may have several webpages, e.g., the Science section (the website) will have books on heat, sound, thermodynamics, statics, etc. (the webpages). Webpages can each be found at a unique location (URL).
* The search index is like the search engine. Each book has its own unique location in the library (two books cannot be kept at the same place) which is specified by the catalog number.
Active learning
---------------

*There is no active learning available yet. Please, consider contributing.*

Deeper dive
-----------

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

### Web page

A **web page** is a simple document displayable by a browser. Such documents are written in the HTML language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

* *style information* — controlling a page's look-and-feel
* *scripts* — which add interactivity to the page
* *media* — images, sounds, and videos.

**Note:** Browsers can also display other documents such as PDF files or images, but the term **web page** specifically refers to HTML documents. Otherwise, we only use the term **document**.

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

![Example of a web page address in the browser address bar](/en-US/docs/Learn/Common_questions/Web_mechanics/Pages_sites_servers_and_search_engines/web-page.jpg)

### Website

A *website* is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portions of text—that allow the user to move from one page of the website to another.

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or *homepage* (casually referred as "the home"):

![Example of a website domain name in the browser address bar](/en-US/docs/Learn/Common_questions/Web_mechanics/Pages_sites_servers_and_search_engines/web-site.jpg)

Note that it is also possible to have a *single-page website*: a site that consists of a single web page which is dynamically updated with new content when needed.

### Web server

A *web server* is a computer hosting one or more *websites*. "Hosting" means that all the *web pages* and their supporting files are available on that computer. The *web server* will send any *web page* from the *website* it is hosting to any user's browser, per user request.

Don't confuse *websites* and *web servers*. For example, if you hear someone say, "My website is not responding", it actually means that the *web server* is not responding and therefore the *website* is not available. More importantly, since a web server can host multiple websites, the term *web server* is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

### Search engine

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from *other* websites.

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

Many beginners on the web confuse search engines and browsers. Let's make it clear: A ***browser*** is a piece of software that retrieves and displays web pages; a ***search engine*** is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

Here is an instance of Firefox showing a Google search box as its default startup page:

![Example of Firefox nightly displaying a custom Google page as default](/en-US/docs/Learn/Common_questions/Web_mechanics/Pages_sites_servers_and_search_engines/search-engine.jpg)

Next steps
----------

* Dig deeper: What is a web server
* See how web pages are linked into a website: Understanding links on the web


What is a Domain Name? - Learn web development

What is a Domain Name?
======================

|  |  |
| --- | --- |
| Prerequisites: |
 First you need to know
 how the Internet works
 and understand
 what URLs are.
  |
| Objective: | Learn what domain names are, how they work, and why they are important. |

Summary
-------

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

Any Internet-connected computer can be reached through a public IP Address, either an IPv4 address (e.g. `192.0.2.172`) or an IPv6 address (e.g., `2001:db8:8b73:0000:0000:8a2e:0370:1337`).

Computers can handle such addresses easily, but people have a hard time finding out who is running the server or what service the website offers. IP addresses are hard to remember and might change over time.

To solve all those problems we use human-readable addresses called domain names.

Deeper dive
-----------

### Structure of domain names

A domain name has a simple structure made of several parts (it might be one part only, two, three…), separated by dots and **read from right to left**:

![Anatomy of the MDN domain name](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_domain_name/structure.png)

Each of those parts provides specific information about the whole domain name.

TLD (Top-Level Domain).

TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (`.com`, `.org`, `.net`) don't require web services to meet any particular criteria, but some TLDs enforce stricter policies so it is clearer what their purpose is. For example:

* Local TLDs such as `.us`, `.fr`, or `.se` can require the service to be provided in a given language or hosted in a certain country — they are supposed to indicate a resource in a particular language or country.
* TLDs containing `.gov` are only allowed to be used by government departments.
* The `.edu` TLD is only for use by educational and academic institutions.

TLDs can contain special as well as latin characters. A TLD's maximum length is 63 characters, although most are around 2–3.

The full list of TLDs is maintained by ICANN.

Label (or component)

The labels are what follow the TLD. A label is a case-insensitive character sequence anywhere from one to sixty-three characters in length, containing only the letters `A` through `Z`, digits `0` through `9`, and the '-' character (which may not be the first or last character in the label). `a`, `97`, and `hello-strange-person-16-how-are-you` are all examples of valid labels.

The label located right before the TLD is also called a *Secondary Level Domain* (SLD).

A domain name can have many labels (or components). It is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a valid domain name. For any domain you control (e.g. mozilla.org), you can create "subdomains" with different content located at each, like developer.mozilla.org, iot.mozilla.org, or bugzilla.mozilla.org.

### Buying a domain name

#### Who owns a domain name?

You cannot "buy a domain name". This is so that unused domain names eventually become available to be used again by someone else. If every domain name was bought, the web would quickly fill up with unused domain names that were locked and couldn't be used by anyone.

Instead, you pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

**Note:** For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under `.fire` is managed by Amazon.

#### Finding an available domain name

To find out whether a given domain name is available,

* Go to a domain name registrar's website. Most of them provide a "whois" service that tells you whether a domain name is available.
* Alternatively, if you use a system with a built-in shell, type a `whois` command into it, as shown here for `mozilla.org`:

```bash
whois mozilla.org
```

This will output the following:
```

Domain Name:MOZILLA.ORG
Domain ID: D1409563-LROR
Creation Date: 1998-01-24T05:00:00Z
Updated Date: 2013-12-08T01:16:57Z
Registry Expiry Date: 2015-01-23T05:00:00Z
Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
Sponsoring Registrar IANA ID: 292
WHOIS Server:
Referral URL:
Domain Status: clientDeleteProhibited
Domain Status: clientTransferProhibited
Domain Status: clientUpdateProhibited
Registrant ID:mmr-33684
Registrant Name:DNS Admin
Registrant Organization:Mozilla Foundation
Registrant Street: 650 Castro St Ste 300
Registrant City:Mountain View
Registrant State/Province:CA
Registrant Postal Code:94041
Registrant Country:US
Registrant Phone:+1.6509030800
```

As you can see, I can't register `mozilla.org` because the Mozilla Foundation has already registered it.

On the other hand, let's see if I could register `afunkydomainname.org`:

```bash
whois afunkydomainname.org
```

This will output the following (at the time of writing):
```

NOT FOUND
```

As you can see, the domain does not exist in the `whois` database, so we could ask to register it. Good to know!

#### Getting a domain name

The process is quite straightforward:

1. Go to a registrar's website.
2. Usually there is a prominent "Get a domain name" call to action. Click on it.
3. Fill out the form with all required details. Make sure, especially, that you have not misspelled your desired domain name. Once it's paid for, it's too late!
4. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.

**Note:** In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

#### DNS refreshing

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few special servers called "authoritative name servers" or "top-level DNS servers" — these are like the boss servers that manage the system.

Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server and fetches the updated information from it). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

### How does a DNS request work?

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

1. Type `mozilla.org` in your browser's location bar.
2. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
3. If your computer does not know which IP is behind the `mozilla.org` name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
4. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.

![Explanation of the steps needed to obtain the result to a DNS request](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_domain_name/2014-10-dns-request2.png)

Next steps
----------

Okay, we talked a lot about processes and architecture. Time to move on.

* If you want to get hands-on, it's a good time to start digging into design and explore the anatomy of a web page.
* It's also worth noting that some aspects of building a website cost money. Please refer to how much it costs to build a website.
* Or read more about Domain Names on Wikipedia.
* You can also find here a fun and colorful explanation of how DNS works.


What is a URL? - Learn web development

What is a URL?
==============

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

|  |  |
| --- | --- |
| Prerequisites: |
 You need to first know
 how the Internet works,
 what a Web server is
 and
 the concepts behind links on the web.
  |
| Objective: | You will learn what a URL is and how it works on the Web. |

Summary
-------

With Hypertext and HTTP, ***URL*** is one of the key concepts of the Web. It is the mechanism used by browsers to retrieve any published resource on the web.

**URL** stands for *Uniform Resource Locator*. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

Basics: anatomy of a URL
------------------------

Here are some examples of URLs:
```

https://developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Learn/
https://developer.mozilla.org/en-US/search?q=URL
```

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

A URL is composed of different parts, some mandatory and others optional. The most important parts are highlighted on the URL below (details are provided in the following sections):

![full URL](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-all.png)

**Note:** You might think of a URL like a regular postal mail address: the *scheme* represents the postal service you want to use, the *domain name* is the city or town, and the *port* is like the zip code; the *path* represents the building where your mail should be delivered; the *parameters* represent extra information such as the number of the apartment in the building; and, finally, the *anchor* represents the actual person to whom you've addressed your mail.

**Note:** There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don't worry about this, you don't need to know them to build and use fully functional URLs.

Scheme
------

![Scheme](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-protocol@x2_update.png)

The first part of the URL is the *scheme*, which indicates the protocol that the browser must use to request the resource (a protocol is a set method for exchanging or transferring data around a computer network). Usually for websites the protocol is HTTPS or HTTP (its unsecured version). Addressing web pages requires one of these two, but browsers also know how to handle other schemes such as `mailto:` (to open a mail client), so don't be surprised if you see other protocols.

Authority
---------

![Authority](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-authority.png)

Next follows the *authority*, which is separated from the scheme by the character pattern `://`. If present the authority includes both the *domain* (e.g. `www.example.com`) and the *port* (`80`), separated by a colon:

* The domain indicates which Web server is being requested. Usually this is a domain name, but an IP address may also be used (but this is rare as it is much less convenient).
* The port indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.

**Note:** The separator between the scheme and authority is `://`. The colon separates the scheme from the next part of the URL, while `//` indicates that the next part of the URL is the authority.

One example of a URL that doesn't use an authority is the mail client (`mailto:foobar`). It contains a scheme but doesn't use an authority component. Therefore, the colon is not followed by two slashes and only acts as a delimiter between the scheme and mail address.

Path to resource
----------------

![Path to the file](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-path@x2.png)

`/path/to/myfile.html` is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.

Parameters
----------

![Parameters](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-parameters@x2.png)

`?key1=value1&key2=value2` are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the `&` symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.

Anchor
------

![Anchor](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL/mdn-url-anchor@x2.png)

`#SomewhereInTheDocument` is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the **#**, also known as the **fragment identifier**, is never sent to the server with the request.

How to use URLs
---------------

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

The HTML language — which will be discussed later on — makes extensive use of URLs:

* to create links to other documents with the `<a>` element;
* to link a document with its related resources through various elements such as `<link>` or `<script>`;
* to display media such as images (with the `<img>` element), videos (with the `<video>` element), sounds and music (with the `<audio>` element), etc.;
* to display other HTML documents with the `<iframe>` element.

**Note:** When specifying URLs to load resources as part of a page (such as when using the `<script>`, `<audio>`, `<img>`, `<video>`, and the like), you should generally only use HTTP and HTTPS URLs, with few exceptions (one notable one being `data:`; see Data URLs). Using FTP, for example, is not secure and is no longer supported by modern browsers.

Other technologies, such as CSS or JavaScript, use URLs extensively, and these are really the heart of the Web.

Absolute URLs vs. relative URLs
-------------------------------

What we saw above is called an *absolute URL*, but there is also something called a *relative URL*. The URL standard defines both — though it uses the terms *absolute URL string* and *relative URL string*, to distinguish them from URL objects (which are in-memory representations of URLs).

Let's examine what the distinction between *absolute* and *relative* means in the context of URLs.

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or *absolute*) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

When a URL is used within a document, such as in an HTML page, things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an *absolute URL* and a *relative URL* by looking only at the *path* part of the URL. If the path part of the URL starts with the "`/`" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

Let's look at some examples to make this clearer.

### Examples of absolute URLs

|  |  |
| --- | --- |
| Full URL (the same as the one we used before) |
```
https://developer.mozilla.org/en-US/docs/Learn
```
 |
| Implicit protocol |
```
//developer.mozilla.org/en-US/docs/Learn
```

 In this case, the browser will call that URL with the same protocol as
 the one used to load the document hosting that URL.
  |
| Implicit domain name |
```
/en-US/docs/Learn
```

 This is the most common use case for an absolute URL within an HTML
 document. The browser will use the same protocol and the same domain
 name as the one used to load the document hosting that URL.
 **Note:**
*it isn't possible to omit the domain name without omitting the
protocol as well*.
  |

### Examples of relative URLs

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: `https://developer.mozilla.org/en-US/docs/Learn`

|  |  |
| --- | --- |
| Sub-resources |
```
Skills/Infrastructure/Understanding_URLs
```

 Because that URL does not start with `/`, the browser will
 attempt to find the document in a subdirectory of the one containing
 the current resource. So in this example, we really want to reach
 this URL:
 https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding\_URLs.
  |
| Going back in the directory tree |
```
../CSS/display
```

 In this case, we use the `../` writing convention —
 inherited from the UNIX file system world — to tell the browser we
 want to go up from one directory. Here we want to reach this URL:
 https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which
 can be simplified to:
 https://developer.mozilla.org/en-US/docs/CSS/display.
  |

Semantic URLs
-------------

Despite their very technical flavor, URLs represent a human-readable entry point for a website. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called *semantic URLs*. Semantic URLs use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages to creating human-readable URLs:

* It is easier for you to manipulate them.
* It clarifies things for users in terms of where they are, what they're doing, what they're reading or interacting with on the Web.
* Some search engines can use those semantics to improve the classification of the associated pages.
See also
--------

Data URLs: URLs prefixed with the `data:` scheme, allow content creators to embed small files inline in documents.


MathML first steps overview - Learn web development

MathML first steps overview
===========================

MathML is the markup language used to write mathematical formulas in web pages. This module provides a gentle beginning to your path towards MathML mastery with the basics of how it works, what the syntax looks like, and how you can start using it inside HTML.

#### Looking to become a front-end web developer?

We have put together a course that includes all the essential information you need to work towards your goal.

**Get started**

Prerequisites
-------------

Before starting this module, you should have:

1. Basic familiarity with using computers and using the Web passively (i.e. looking at it, consuming the content.)
2. A basic work environment set up, as detailed in Installing basic software, and an understanding of how to create and manage files, as detailed in Dealing with files.
3. Basic familiarity with HTML, as described in Introduction to HTML.

**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out the code examples in an online coding program such as JSBin or Glitch.

Guides
------

This module contains the following articles, which will take you through all the basic theory of MathML, and provide opportunities for you to test out some skills.

Getting started with MathML

In this article, we will take a simple HTML document and see how to add MathML formulas into it, introducing a few elements along the way.

Text containers

Now that you get a better idea of MathML, we move on to text containers (variables, numbers, operators, ...) which are used as building blocks of MathML formulas.

Fractions and roots

Relying on text containers, this article describes how to build more complex MathML expressions by nesting fractions and roots.

Scripts

We continue the review of basic math notations and focuses on building MathML elements with scripts.

Tables

Once all basic math notations are known, it remains to consider tabular layout which can be used for matrix-like expressions and other advanced math layout.

Assessments
-----------

The following assessment will test your understanding of the MathML basics covered in the guides above.

Three famous mathematical formulas

With the things you have learned in the last few articles, you should already be able to write relatively sophisticated MathML formulas. This assessment gives you a chance to do that.


MathML scripted elements - Learn web development

MathML scripted elements
========================

* Previous
* Overview: First steps
* Next

We continue the review of basic math notations and focus on building MathML elements with scripts.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, and HTML basics (study
 Introduction to HTML.)
  |
| Objective: | To get familiar with basic MathML elements producing scripted elements. |

Subscripts and superscripts
---------------------------

Similarly to what we saw in the previous article, the `<msub>`, `<msup>` and `<msubsup>` have a special structure expecting exactly two elements (for `<msub>`, `<msup>`) or three elements (for `<msubsup>`):

```html
<p>
  msub:
  <math>
    <msub>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
    </msub>
  </math>
</p>

<p>
  msup:
  <math>
    <msup>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
    </msup>
  </math>
</p>
<p>
  msubsup:
  <math>
    <msubsup>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
      <mtext>child3</mtext>
    </msubsup>
  </math>
</p>
```

Below is the rendering of the above example in your browser.

You should notice that:

* The second child of the `<msub>` element is attached as a subscript of its first child.
* The second child of the `<msup>` element is attached as a superscript of its first child.
* The second and third children of the `<msubsup>` element are respectively attached as a subscript and superscript of its first child.
* The text inside scripts is scaled down.

**Note:** The MathML elements `<msub>` and `<msup>` are different from the HTML elements `<sub>` and `<sup>`. They allow authors to provide arbitrary MathML subtrees as scripts, not just text.

Underscripts and overscripts
----------------------------

The `<munder>`, `<mover>` and `<munderover>` elements are very similar except that they are used to attach underscripts and overscripts. Instead of giving details, we will let you figure out their definitions yourself with the following exercise.

### Active learning: Recognize under/over scripts

In the following example, try to guess the names of the mystery elements (written as question marks) and click the button to reveal the solution:
```

<p>
  <code><<span>????????</span>></code> element with exactly two children
  (child1, child2):
  <math>
    <mover>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
    </mover>
  </math>
</p>
<p>
  <code><<span>????????</span>></code> element with exactly three children
  (child1, child2 and child3):
  <math>
    <munderover>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
      <mtext>child3</mtext>
    </munderover>
  </math>
</p>
<p>
  <code><<span>????????</span>></code> element with exactly two children
  (child1, child2):
  <math>
    <munder>
      <mtext>child1</mtext>
      <mtext>child2</mtext>
    </munder>
  </math>
</p>

<p><input type="button" id="showSolution" value="Show solution" /></p>
```

```
p {
  padding: 0.5em;
}
```

```
document.getElementById("showSolution").addEventListener("click", () => {
  const maths = Array.from(document.getElementsByTagName("math"));
  Array.from(document.getElementsByTagName("span")).forEach((span, index) => {
    span.textContent = maths[index].firstElementChild.tagName;
  });
});
```

### Active learning: Recognize scripted elements

The following MathML formula contains a more complex expression, nesting fractions, roots and scripts. Try to guess the elements laid out with scripted elements `<msub>`, `<msup>`, `<msubsup>`, `<munder>`, `<mover>`, `<munderover>`. Each time you click such an element, it is highlighted and a confirmation message is displayed. Finally, read the MathML source to verify whether that corresponds to your expectation.
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with scripted elements</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mroot>
        <mrow>
          <munder>
            <mi>β</mi>
            <mo>⎵</mo>
          </munder>
        </mrow>
        <mn>3</mn>
      </mroot>
      <mo>+</mo>
      <mfrac>
        <mrow
 ><mo>|</mo>
          <mover>
            <mi>α</mi>
            <mo>→</mo>
          </mover>
          <mo>|</mo>
        </mrow>
        <msup>
          <mi>s</mi>
          <mn>3</mn>
        </msup>
      </mfrac>
      <mo>−</mo>
      <mrow>
        <munderover>
          <mo>∑</mo>
          <mrow>
            <mi>i</mi>
            <mo>=</mo>
            <mn>1</mn>
          </mrow>
          <mi>n</mi>
        </munderover>
        <msqrt>
          <mrow>
            <msub>
              <mi>a</mi>
              <mi>i</mi>
            </msub>
            <mo>−</mo>
            <msubsup>
              <mi>K</mi>
              <mn>0</mn>
              <mi>i</mi>
            </msubsup>
          </mrow>
        </msqrt>
      </mrow>
    </math>
    <input type="button" id="clearOutput" value="Reset" />
    <div id="output"></div>
  </body>
</html>
```

```
.highlight {
  color: red;
}
math {
  font-size: 200%;
}
```

```
const scriptedElements = Array.from(
  document.querySelectorAll("msub, msup, msubsup, munder, mover, munderover"),
);
const outputDiv = document.getElementById("output");
function clearHighlight() {
  scriptedElements.forEach((scripted) => {
    scripted.classList.remove("highlight");
  });
}
scriptedElements.forEach((scripted) => {
  scripted.addEventListener("click", () => {
    clearHighlight();
    scripted.classList.add("highlight");
    outputDiv.insertAdjacentHTML(
      "beforeend",
      `<p><strong>You clicked an <code><${scripted.tagName}></code> element.</strong></p>`,
    );
  });
});
document.getElementById("clearOutput").addEventListener("click", () => {
  clearHighlight();
  outputDiv.innerHTML = "";
});
```

More operator properties
------------------------

We have previously seen some properties of the `<mo>` element namely stretching in the vertical direction and spacing. Now that scripted elements are available, we can extend that list. We will do that by tweaking our previous example.

### Stretching in horizontal direction

Let's first perform the substitutions

β
≔

z
1

+

z
2

 and

α
≔

v
1

+

v
2

:
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with horizontal stretchy operators</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mroot>
        <mrow>
          <munder>
            <mrow>
              <msub>
                <mi>z</mi>
                <mn>1</mn>
              </msub>
              <mo>+</mo>
              <msub>
                <mi>z</mi>
                <mn>2</mn>
              </msub>
            </mrow>
            <mo>⎵</mo>
          </munder>
        </mrow>
        <mn>3</mn>
      </mroot>
      <mo>+</mo>
      <mfrac>
        <mrow
 ><mo>|</mo>
          <mover>
            <mrow>
              <msub>
                <mi>v</mi>
                <mn>1</mn>
              </msub>
              <mo>+</mo>
              <msub>
                <mi>v</mi>
                <mn>2</mn>
              </msub>
            </mrow>
            <mo>→</mo>
          </mover>
          <mo>|</mo>
        </mrow>
        <msup>
          <mi>s</mi>
          <mn>3</mn>
        </msup>
      </mfrac>
      <mo>−</mo>
      <mrow>
        <munderover>
          <mo>∑</mo>
          <mrow>
            <mi>i</mi>
            <mo>=</mo>
            <mn>1</mn>
          </mrow>
          <mi>n</mi>
        </munderover>
        <msqrt>
          <mrow>
            <msub>
              <mi>a</mi>
              <mi>i</mi>
            </msub>
            <mo>−</mo>
            <msubsup>
              <mi>K</mi>
              <mn>0</mn>
              <mi>i</mi>
            </msubsup>
          </mrow>
        </msqrt>
      </mrow>
    </math>
  </body>
</html>
```

```
.highlight {
  color: red;
}
math {
  font-size: 200%;
}
```

We now realize that the bottom bracket "⎵" and the rightward arrow "→" stretch horizontally to cover the width of the substituted values. Recall that some vertical operators can stretch to cover the height of non-stretchy siblings inside an `<mrow>`. Similarly some horizontal operators can stretch to cover the width of non-stretchy siblings in an `<munder>`, `<mover>` or `<munderover>` element.

**Note:** Stretching can happen for any child of the `<munder>`, `<mover>` or `<munderover>` element, not just the underscript or overscript.

### Large operator and limits

So far our example has actually been rendered with the `display="block"` attribute. Let's look at the same example, as rendered without that attribute:
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with moved limits and small largeop</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math>
      <mroot>
        <mrow>
          <munder>
            <mrow>
              <msub>
                <mi>z</mi>
                <mn>1</mn>
              </msub>
              <mo>+</mo>
              <msub>
                <mi>z</mi>
                <mn>2</mn>
              </msub>
            </mrow>
            <mo>⎵</mo>
          </munder>
        </mrow>
        <mn>3</mn>
      </mroot>
      <mo>+</mo>
      <mfrac>
        <mrow
 ><mo>|</mo>
          <mover>
            <mrow>
              <msub>
                <mi>v</mi>
                <mn>1</mn>
              </msub>
              <mo>+</mo>
              <msub>
                <mi>v</mi>
                <mn>2</mn>
              </msub>
            </mrow>
            <mo>→</mo>
          </mover>
          <mo>|</mo>
        </mrow>
        <msup>
          <mi>s</mi>
          <mn>3</mn>
        </msup>
      </mfrac>
      <mo>−</mo>
      <mrow>
        <munderover>
          <mo>∑</mo>
          <mrow>
            <mi>i</mi>
            <mo>=</mo>
            <mn>1</mn>
          </mrow>
          <mi>n</mi>
        </munderover>
        <msqrt>
          <mrow>
            <msub>
              <mi>a</mi>
              <mi>i</mi>
            </msub>
            <mo>−</mo>
            <msubsup>
              <mi>K</mi>
              <mn>0</mn>
              <mi>i</mi>
            </msubsup>
          </mrow>
        </msqrt>
      </mrow>
    </math>
  </body>
</html>
```

```
.highlight {
  color: red;
}
math {
  font-size: 200%;
}
```

As expected, the formula is no longer centered and the rendering is modified to minimized the height. Focusing on the summation symbol, one can notice that the sigma is drawn smaller and that the scripts of the `<munderover>` element are now attached as a subscript and a superscript! This is due to two properties of the "∑" operator:

* *largeop*: The operator is drawn with a bigger glyph if the `<math>` tag has a `display="block"` attribute.
* *movablelimits*: The underscripts and overscripts attached to the operator are respectively rendered as subscripts and superscripts if the `<math>` tag does not have the `display="block"` attribute.

**Note:** The *largeop* property is actually unrelated to scripts, even though operators having this property are typically scripted. The *movablelimits* property is taken into account for `<munder>` and `<mover>` elements too.

Summary
-------

In this article, we've finished reviewing basic layout introducing elements `<msub>`, `<msup>`, `<msubsup>`, `<munder>`, `<mover>`, `<munderover>` for subscripts, superscripts, underscripts and overscripts. Using these elements, we were able to briefly introduce new properties of the `<mo>` element. In the next article, we will continue focus on tabular layout.

* Previous
* Overview: First steps
* Next
See also
--------

* The `<msub>` element
* The `<msup>` element
* The `<msubsup>` element
* The `<munder>` element
* The `<mover>` element
* The `<munderover>` element


MathML fractions and roots - Learn web development

MathML fractions and roots
==========================

* Previous
* Overview: First steps
* Next

Relying on text containers, this article describes how to build more complex MathML expressions by nesting fractions and roots.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, and HTML basics (study
 Introduction to HTML.)
  |
| Objective: |
 To get familiar with MathML elements used for writing fractions and
 square roots.
  |

Subtrees of <mfrac>, <msqrt> and <mroot>
----------------------------------------

In the getting started with MathML article, we've already met the `<mfrac>` element to describe a fraction. Let's consider a basic example which adds new elements for roots (`<msqrt>` and `<mroot>`):

```html
<math>
  <mfrac>
    <mtext>child1</mtext>
    <mtext>child2</mtext>
  </mfrac>
</math>
<br />
<math>
  <msqrt>
    <mtext>child1</mtext>
    <mtext>child2</mtext>
    <mtext>...</mtext>
    <mtext>childN</mtext>
  </msqrt>
</math>
<br />
<math>
  <mroot>
    <mtext>child1</mtext>
    <mtext>child2</mtext>
  </mroot>
</math>
```

Below is a screenshot of how it is rendered by a browser:

![Screenshot of mfrac, msqrt, mroot](/en-US/docs/Learn/MathML/First_steps/Fractions_and_roots/mfrac-msqrt-mroot.png)

* We already know that the `<mfrac>` element is rendered as a fraction: The first child (the numerator) is drawn above the second child (the denominator) separated by a horizontal bar.
* The `<msqrt>` is rendered as a square root: its children are laid out like an `<mrow>`, prefixed by a root symbol √ and completely covered by an overbar.
* Finally, the `<mroot>` element is rendered as an nth root: The first element is covered by the radical symbol while the second element is used as the degree of the root and rendered as a prefix superscript.
### Active learning: nesting different elements

Here is a simple exercise to verify whether you understood the relation between a MathML subtree and its visual rendering. The document contains a MathML formula and you must check all subtrees corresponding to a subtree in that MathML formula. Once you are done, you can inspect the source of the MathML formula and verify if it matches your expectation.
```

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8"/>
    <title>My page with math characters</title>
    <link rel="stylesheet" href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css">
  </head>
  <body>
  <p>
    <math>
    <mfrac id="mfrac1">
      <msqrt id="msqrt1">
        <mn>2</mn>
      </msqrt>
      <mroot id="mroot1">
        <mn>4</mn>
        <mn>3</mn>
      </mroot>
    </mfrac>
    <mo>+</mo>
    <mroot id="mroot2">
      <mn>5</mn>
      <mfrac id="mfrac2">
        <mn>6</mn>
        <mn>7</mn>
      </mfrac>
    </mroot>
    <mo>+</mo>
    <msqrt id="msqrt2">
      <mn>8</mn>
      <mo>−</mo>
      <mn>9</mn>
    </msqrt>
  </p>

  <ol id="options">
    <li>
      <input type="checkbox" data-comment="Verify the order of children in an mfrac!">
      An mfrac with an mroot as its first child and an msqrt as its second child.
    </li>
    <li>
      <input type="checkbox" data-highlight="mroot2" data-comment="The '6 over 7'-th root of five.">
      An mroot with an mn as its first child and mfrac as its second child.
    </li>
    <li>
      <input type="checkbox" data-comment="This formula does not contain any fraction inside a square root!">
      An msqrt containing an mfrac element.
   </li>
    <li>
      <input type="checkbox" data-comment="The square root of two." data-highlight="msqrt1">
      An msqrt with one mn child.
    </li>
    <li>
      <input type="checkbox" data-comment="Verify the order of children in an mroot!">
      An mroot with an mfrac as its first child and mn as its second child.
    </li>
    <li>
      <input type="checkbox" data-comment="The square root of 'eight minus nine'." data-highlight="msqrt2">
      An msqrt with the following list of children: mn, mo, mn.
    </li>
    <li>
      <input type="checkbox" data-comment="The square root of two over the cubic root of four." data-highlight="mfrac1">
      An mfrac with an msqrt as its first child and an mroot as its second child.
    </li>
    <li>
      <input type="checkbox" data-comment="mfrac must have exactly two children!">
      An mfrac with the following list of children: msqrt, mn, msqrt.
    </li>
    <li>
      <input type="checkbox" data-comment="mroot must have exactly two children!">
      An mroot with one mn child.
    </li>
    <li>
      <input type="checkbox" data-comment="The fraction six over seven." data-highlight="mfrac2">
      An mfrac with two mn children.
    </li>
    <li>
      <input type="checkbox" data-comment="This formula does not contain any square root with more than two numbers!">
      An msqrt with five mn children.
    </li>
    <li>
      <input type="checkbox" data-highlight="mroot1" data-comment="The cubic root of four.">
      An mroot with two mn children.
    </li>
  </ol>
  <p>
    <strong id="comment"></strong>
  </p>
  <p>
    <strong id="status"></strong>
  </p>
  </body>
```

```
math {
  font-family:
    Latin Modern Math,
    STIX Two Math;
  font-size: 200%;
}
math .highlight {
  background: pink;
}
math [id] .highlight {
  background: lightblue;
}
p {
  padding: 0.5em;
}
```

```
const options = document.getElementById("options");
const comment = document.getElementById("comment");
const checkboxes = Array.from(options.getElementsByTagName("input"));
const status = document.getElementById("status");
function verifyOption(checkbox) {
  let mathml = checkbox.dataset.highlight;
  if (mathml) {
    mathml = document.getElementById(mathml);
  }
  if (checkbox.checked) {
    comment.textContent = checkbox.dataset.comment;
    if (mathml) {
      mathml.classList.add("highlight");
    } else {
      checkbox.checked = false;
    }
  } else {
    comment.textContent = "";
    if (mathml) {
      mathml.classList.remove("highlight");
    }
  }
  const finished = checkboxes.every(
    (checkbox) => !!checkbox.checked === !!checkbox.dataset.highlight,
  );
  status.textContent = finished
    ? "Congratulations, you checked all the correct answers!"
    : "";
}
checkboxes.forEach((checkbox) => {
  checkbox.addEventListener("change", () => {
    verifyOption(checkbox);
  });
});
```

Stretchy radical symbols
------------------------

As previously seen, the overbar of the `<msqrt>` and `<mroot>` elements stretches horizontally to cover their content. But actually the root symbol √ also stretches to be as tall as their content.
```

<link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```

```html
<math display="block">
  <mroot>
    <msqrt>
      <mfrac>
        <mn>1</mn>
        <mn>2</mn>
      </mfrac>
    </msqrt>
    <mn>3</mn>
  </mroot>
</math>
```

**Warning:** Special math fonts are generally required to make that stretching possible, the previous example relies on web fonts.

Fractions without bar
---------------------

Some mathematical concepts are sometimes written using fraction-like notations such binomial coefficients or Legendre symbols. It is appropriate to use an `<mfrac>` element to markup such notations. For fraction-like notations that don't draw a horizontal bar, attach a `linethickness="0"` attribute to the `<mfrac>` element:
```

<link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```

```html
<math display="block">
  <mrow>
    <mo>(</mo>
    <mfrac linethickness="0">
      <mn>3</mn>
      <mn>2</mn>
    </mfrac>
    <mo>)</mo>
  </mrow>
  <mo>=</mo>
  <mn>3</mn>
  <mo>≠</mo>
  <mfrac>
    <mn>3</mn>
    <mn>2</mn>
  </mfrac>
</math>
```

**Note:** Although the `linethickness` attribute can be used to specify an arbitrary thickness, it is better to keep the default value, which is calculated from parameters specified in the math font.

Summary
-------

In this lesson, we've seen how to build fractions and roots using the `<mfrac>`, `<msqrt>` and `<mroot>` elements. We noticed some special feature of these elements, namely the fraction and radical symbol. We've seen how to use the `linethickness` attribute to draw fractions without bars. In the next article, we will continue with basic math notations and consider scripts.

* Previous
* Overview: First steps
* Next
See also
--------

* The `<mfrac>` element
* The `<msqrt>` element
* The `<mroot>` element


Three famous mathematical formulas - Learn web development

Three famous mathematical formulas
==================================

* Previous
* Overview: First steps

|  |  |
| --- | --- |
| Prerequisites: |
 Before attempting this assessment you should have already worked through
 all the articles in this module, and also have an understanding of HTML
 basics (study
 Introduction to HTML).
  |
| Objective: |
 To have a play with some MathML and test your new-found
 knowledge.
  |

A small math article
--------------------

The goal is to rewrite the following math article using HTML and MathML:

![Screenshot of the PDF output generated by XeLaTeX](/en-US/docs/Learn/MathML/First_steps/Three_famous_mathematical_formulas/xelatex-output.png)

Although you don't need to be familiar with LaTeX, it might be useful to know the LaTeX source from which it was generated:

```latex
\documentclass{article}

\usepackage{amsmath}
\usepackage{amssymb}

\begin{document}

To solve the cubic equation $t^3 + pt + q = 0$ (where the real numbers
$p, q$ satisfy ${4p^3 + 27q^2} > 0$) one can use Cardano's formula:

\[
 \sqrt[{3}]{
 -\frac{q}{2}
 +\sqrt{\frac{q^2}{4} + {\frac{p^{3}}{27}}}
 }+
 \sqrt[{3}]{
 -\frac{q}{2}
 -\sqrt{\frac{q^2}{4} + {\frac{p^{3}}{27}}}
 }
\]

For any $u\_1, \dots, u\_n \in \mathbb{C}$ and
$v\_1, \dots, v\_n \in \mathbb{C}$, the Cauchy–Bunyakovsky–Schwarz
inequality can be written as follows:

\[
 \left| \sum\_{k=1}^n {u\_k \bar{v\_k}} \right|^2
 \leq
 {
 \left( \sum\_{k=1}^n {|u\_k|} \right)^2
 \left( \sum\_{k=1}^n {|v\_k|} \right)^2
 }
\]

Finally, the determinant of a Vandermonde matrix can be calculated
using the following expression:

\[
 \begin{vmatrix}
 1 & x\_1 & x\_1^2 & \dots & x\_1^{n-1} \\
 1 & x\_2 & x\_2^2 & \dots & x\_2^{n-1} \\
 1 & x\_3 & x\_3^2 & \dots & x\_3^{n-1} \\
 \vdots & \vdots & \vdots & \ddots & \vdots \\
 1 & x\_n & x\_n^2 & \dots & x\_n^{n-1} \\
 \end{vmatrix}
 = {\prod\_{1 \leq {i,j} \leq n} {(x\_i - x\_j)}}
\]

\end{document}
```

Starting point
--------------

To get this assessment started, you can rely on our usual HTML template. By default it uses UTF-8 encoding, special Web fonts for the `<body>` and `<math>` tags (with similar look & feel as the LaTeX output). The goal is to replace the question marks `???` with actual MathML content.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Three famous mathematical formulas</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body class="htmlmathparagraph">
    <p>
      To solve the cubic equation ??? (where the real numbers ??? satisfy ???)
      one can use Cardano's formula: ???
    </p>

    <p>
      For any ??? and ???, the Cauchy–Bunyakovsky–Schwarz inequality can be
      written as follows: ???
    </p>

    <p>
      Finally, the determinant of a Vandermonde matrix can be calculated using
      the following expression: ???
    </p>
  </body>
</html>
```

Hints and tips
--------------

* Start by inserting empty `<math>` tags, deciding whether they should have a `display="block"` attribute or not.
* Check the text used and find their Unicode characters ("−", "ℂ", "∑", ...).
* Analyze the semantics of each portion of text (variable? operator? number?) and determine the proper token element to use for each of them.
* Look for advanced constructions (fractions? roots? scripts? matrices?) and determine the proper MathML element to use for each of them.
* Don't forget to rely on `<mrow>` for grouping subexpressions.
* Pay attention to stretchy and large operators!
* Use the W3C validator to catch unintended mistakes in your HTML/MathML markup.
* If you are stuck, or realize how painful it is to write MathML by hand, feel free to use tools to help write MathML such as TeXZilla.
* Previous
* Overview: First steps


MathML Text Containers - Learn web development

MathML Text Containers
======================

* Previous
* Overview: First steps
* Next

Now that you get a better idea of MathML, we move focus on text containers (variables, numbers, operators, ...) which are used as building blocks of MathML formulas.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, HTML basics (study
 Introduction to HTML) and some CSS notions on text styling (read fundamental text and font styling and
 web fonts).
  |
| Objective: |
 To get familiar with MathML elements used for writing text and be aware
 of special behaviors.
  |

Unicode characters for mathematics
----------------------------------

Mathematical formulas involve many special characters, for example greek letters (e.g. Δ), fraktur letters (e.g. 𝔄), double-struck letter (e.g. ℂ), binary operators (e.g. ≠), arrows (e.g. ⇒), integral symbols (e.g. ∮), summation symbols (e.g. ∑), logical symbols (e.g. ∀), fences (e.g. ⌊) and many more. Wikipedia's article Mathematical operators and symbols in Unicode provides a good overview of the characters used.

Since most of these characters are not part of Basic Latin Unicode block, it is recommended to specify your document's character encoding and to serve it with appropriate web fonts. Here is a basic template to use UTF-8 encoding and the Latin Modern Math font:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with math characters</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <p style="font-family: Latin Modern Math">∀A∊𝔰𝔩(n,𝔽),TrA=0</p>
  </body>
</html>
```

A bit of semantics
------------------

We noticed in the getting started with MathML article that the text in MathML formulas are wrapped in specific container elements such as the `<mn>` or `<mo>`. More generally, every text in MathML formulas must be included inside such container elements, called *token* elements. In addition, MathML provides multiple token elements in order to distinguish different meanings of the text content:

* The `<mi>` element, which represents an "identifier" which could be a symbolic name or arbitrary text. Examples: `<mi>x</mi>` (variable), `<mi>cos</mi>` (function name) and `<mi>π</mi>` (symbolic constant).
* The `<mn>` element represents a "numeric literal" or other data that should be rendered as a numeric literal. Examples: `<mn>2</mn>` (integer), `<mn>0.123</mn>` (decimal number) or `<mn>0xFFEF</mn>` (hexadecimal value).
* The `<mo>` element represents an operator or anything that should be rendered as an operator. For example `<mo>+</mo>` (binary operation), `<mo>≤</mo>` (binary relation), `<mo>∑</mo>` (summation symbol) or `<mo>[</mo>` (fence).
* The `<mtext>` element is used to represent arbitrary text. For example short words in formulas such as `<mtext>if<mtext>` or `<mtext>maps to</mtext>`.
### Active learning: recognize token elements

Below is a more complex example, which says that the absolute value of a real number is equal to that number if and only if it is nonnegative. Spot the different token elements and what they are used for. Each time you click the corresponding text, it is highlighted and a confirmation message is displayed.
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with math characters</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mrow>
        <mrow>
          <mo>|</mo>
          <mi>x</mi>
          <mo>|</mo>
        </mrow>
        <mo>=</mo>
        <mi>x</mi>
      </mrow>
      <mtext> iff </mtext>
      <mrow>
        <mi>x</mi>
        <mo>≥</mo>
        <mn>0</mn>
      </mrow>
    </math>
    <input type="button" id="clearOutput" value="Reset" />
    <div id="output"></div>
  </body>
</html>
```

```
.highlight {
  color: red;
}
math {
  font-size: 200%;
}
```

```
const tokenElements = Array.from(
  document.querySelectorAll("mi, mo, mn, mtext"),
);
const outputDiv = document.getElementById("output");
function clearHighlight() {
  tokenElements.forEach((token) => {
    token.classList.remove("highlight");
  });
}
tokenElements.forEach((token) => {
  token.addEventListener("click", () => {
    clearHighlight();
    token.classList.add("highlight");
    outputDiv.insertAdjacentHTML(
      "beforeend",
      `<p><strong>You clicked an <code><${token.tagName}></code> element.</strong></p>`,
    );
  });
});
document.getElementById("clearOutput").addEventListener("click", () => {
  clearHighlight();
  outputDiv.innerHTML = "";
});
```

Finally, read the MathML source to verify whether that corresponds to your expectation:

```xml
<math display="block">
  <mrow>
    <mrow>
      <mo>|</mo>
      <mi>x</mi>
      <mo>|</mo>
    </mrow>
    <mo>=</mo>
    <mi>x</mi>
  </mrow>
  <mtext> iff </mtext>
  <mrow>
    <mi>x</mi>
    <mo>≥</mo>
    <mn>0</mn>
  </mrow>
</math>
```

**Note:** It is sometimes difficult to decide the token element to use for a given text content. In practice, choosing the wrong element should not cause major issues because all token elements are generally rendered the same by browser implementations (for visual display and for assistive technologies). However, the `<mi>` and `<mo>` elements have special distinguishing features that one should be aware of. They are explained in the following sections.

Automatic italicization of <mi>
-------------------------------

One typographic convention in mathematics is to use italic letters for variables. In order to help with that, `<mi>` elements with a single character may be automatically rendered as italic. This is the case for all the letters from the latin and greek alphabets. Compare the rendering of the two `<mi>` elements in the following formula:

```html
<math>
  <mi>sin</mi>
  <mi>x</mi>
</math>
```

**Note:** This table from MathML Core provide the exhaustive list of characters that are subject to italicization, together with the corresponding italic characters.

Reverting automatic italicization of <mi>
-----------------------------------------

 In order to revert this default italic transformation you can attach a `mathvariant="normal"` attribute on the `<mi>` element.
 Compare the rendering of the uppercase gamma letters in the following formula:

```html
<math>
  <mi>Γ</mi>
  <mi mathvariant="normal">Γ</mi>
</math>
```

**Note:** Although you can apply this transformation, normally you'd just use the desired Mathematical Alphanumeric Symbols.

Operator properties of <mo>
---------------------------

MathML contains an operator dictionary that defines default properties of `<mo>` elements depending on their content and the position within its container (prefix, infix or postfix). Let's consider a concrete example:

```html
<table>
  <tr>
    <td>Prefix plus</td>
    <td>
      <math>
        <mo>+</mo>
        <mi>i</mi>
      </math>
    </td>
  </tr>
  <tr>
    <td>Infix plus</td>
    <td>
      <math>
        <mi>j</mi>
        <mo>+</mo>
        <mi>i</mi>
      </math>
    </td>
  </tr>
  <tr>
    <td>Prefix sum</td>
    <td>
      <math>
        <mo>∑</mo>
        <mi>i</mi>
      </math>
    </td>
  </tr>
</table>
```

This example should render similarly to the screenshot below. Observe the spacing between the `<mi>i</mi>` elements and its preceding `<mo>`: no spacing for the prefix plus, some spacing for the infix plus and some smaller spacing for the prefix summation symbol.

![Screenshot of the MathML formula with different operator spacing](/en-US/docs/Learn/MathML/First_steps/Text_containers/operator-spacing.png)

Operators have many other properties that we will see in more details later. For now, remember to use an `<mo>` container for characters in the operator dictionary and to properly group subexpressions with `<mrow>` elements in order to help MathML renderers.

### Active learning: spot the difference

Now that you are a bit familiar with special features of `<mi>` and `<mo>`, let's rewrite the `<p>` element in the example at the top of the page with some actual MathML. Compare the visual rendering in your browser and explain the differences with the text-only version.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with math characters</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <p style="font-family: Latin Modern Math">∀A∊𝔰𝔩(n,𝔽),TrA=0</p>
    <p>
      <math>
        <mo>∀</mo>
        <mrow>
          <mi>A</mi>
          <mo>∊</mo>
          <mrow>
            <mi>𝔰𝔩</mi>
            <mrow>
              <mo>(</mo>
              <mi>n</mi>
              <mo>,</mo>
              <mi>𝔽</mi>
              <mo>)</mo>
            </mrow>
          </mrow>
        </mrow>
        <mo>,</mo>
        <mrow>
          <mrow>
            <mi>Tr</mi>
            <mi>A</mi>
          </mrow>
          <mo>=</mo>
          <mn>0</mn>
        </mrow>
      </math>
    </p>
    <input id="showSolution" type="button" value="Show solution" />
    <div id="solution"></div>
  </body>
</html>
```

```
div {
  padding: 0.5em;
}
```

```
document.getElementById("showSolution").addEventListener(
  "click",
  () => {
    document.getElementById("solution").insertAdjacentHTML(
      "beforeEnd",
      `<ul>
 <li><strong>The <code><mi></code> elements containing the "A" and "n" variables are rendered in italic</strong>. However, the <code><mi></code> elements with multiple characters "𝔰𝔩" or whose character is "𝔽" are still rendered upright.</li>
 <li><strong>Spacing is automatically added around the <code><mo></code> elements whose text is "∀", "∊", "=" or a comma</strong>. However, some of them have no spacing added before while the parentheses still have no spacing around them.</li>
 </ul>`,
    );
  },
  { once: true },
);
```

**Note:** An obvious difference is that the source code became much more verbose with MathML. Recall that this tutorial is about learning the language but in practice MathML content is generally not written manually. See the Authoring MathML page for more information.

### Active learning: stretchy operators

The operator dictionary defines a default *stretchy* property as well as corresponding *stretch axis* for some operators. For example, an operator can stretch vertically by default to cover the maximum height of non-stretchy siblings within its `<mrow>` container. By tweaking a bit the previous exercise, one can make operators stretch vertically. Can you find them?
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My page with stretchy operators</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mrow>
        <mrow>
          <mo>|</mo>
          <mfrac>
            <mn>1</mn>
            <mi>x</mi>
          </mfrac>
          <mo>|</mo>
        </mrow>
        <mo>=</mo>
        <mfrac>
          <mn>1</mn>
          <mrow>
            <mo>|</mo>
            <mi>x</mi>
            <mo>|</mo>
          </mrow>
        </mfrac>
        <mo>=</mo>
        <mfrac>
          <mn>1</mn>
          <mi>x</mi>
        </mfrac>
      </mrow>
      <mtext> iff </mtext>
      <mrow>
        <mi>x</mi>
        <mo>≥</mo>
        <mn>0</mn>
      </mrow>
    </math>
    <input type="button" id="clearOutput" value="Reset" />
    <div id="output"></div>
  </body>
</html>
```

```
.highlight {
  color: red;
}
math {
  font-size: 200%;
}
```

```
const tokenElements = Array.from(
  document.querySelectorAll("mi, mo, mn, mtext"),
);
const stretchyMoElements = Array.from(
  document.getElementsByTagName("mo"),
).slice(0, 2);
const outputDiv = document.getElementById("output");
function clearHighlight() {
  tokenElements.forEach((token) => {
    token.classList.remove("highlight");
  });
}
tokenElements.forEach((token) => {
  token.addEventListener("click", () => {
    clearHighlight();
    token.classList.add("highlight");
    let message = "";
    let tagName = `<code><${token.tagName}></code>`;
    if (token.tagName !== "mo") message = `No, this is an ${tagName} element!`;
    else if (!stretchyMoElements.includes(token))
      message = `No, this is an ${tagName} element, but it's not vertically stretched.`;
    else
      message = `Correct, this ${tagName} element is indeed stretched to the height of its <code><mfrac></code> sibling.`;
    outputDiv.insertAdjacentHTML(
      "beforeend",
      `<p><strong>${message}</strong></p>`,
    );
  });
});
document.getElementById("clearOutput").addEventListener("click", () => {
  clearHighlight();
  outputDiv.innerHTML = "";
});
```

As usual, you are invited to read the source code when you are done:

```xml
<math display="block">
  <mrow>
    <mrow>
      <mo>|</mo>
      <mfrac>
        <mn>1</mn>
        <mi>x</mi>
      </mfrac>
      <mo>|</mo>
    </mrow>
    <mo>=</mo>
    <mfrac>
      <mn>1</mn>
      <mrow>
        <mo>|</mo>
        <mi>x</mi>
        <mo>|</mo>
      </mrow>
    </mfrac>
    <mo>=</mo>
    <mfrac>
      <mn>1</mn>
      <mi>x</mi>
    </mfrac>
  </mrow>
  <mtext> iff </mtext>
  <mrow>
    <mi>x</mi>
    <mo>≥</mo>
    <mn>0</mn>
  </mrow>
</math>
```

**Warning:** Special math fonts are generally required to make that stretching possible, the previous example relies on web fonts.

Summary
-------

In this article, we have learnt about a few *token* elements that are used as text containers as well as their different semantics, namely `<mi>` (identifier), `<mn>` (numbers), `<mo>` (operators), `<mtext>` (generic text). We have seen special Unicode characters that are commonly found in math formulas and given an overview of some observable behaviors of the `<mi>` and `<mo>` elements. In the next article, we will see how to rely on *token* elements to build much complex expressions such as fractions and roots.

* Previous
* Overview: First steps
* Next
See also
--------

* The `<mi>` element
* The `<mn>` element
* The `<mo>` element
* The `<mtext>` element


Getting started with MathML - Learn web development

Getting started with MathML
===========================

* Overview: First steps
* Next

In this article, we will take a simple HTML document and see how to add MathML formulas into it, introducing a few elements along the way.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, and HTML basics (study
 Introduction to HTML.)
  |
| Objective: |
 To understand the basic syntax of MathML and how to integrate it in
 HTML pages.
  |

Inserting formulas in HTML via the <math> element
-------------------------------------------------

MathML uses the same syntax as HTML to represent a tree of elements and attributes. In particular, each mathematical formula is represented by an element `<math>` which can be placed inside an HTML page. In the following document, it is inside a paragraph of text:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <title>My first math page</title>
  </head>
  <body>
    <p>
      The fraction
      <math>
        <mfrac>
          <mn>1</mn>
          <mn>3</mn>
        </mfrac>
      </math>
      is not a decimal number.
    </p>
  </body>
</html>
```

The `<mfrac>` element specifies a fraction with a numerator (its first child) and a denominator (its second child). This is how it renders in your browser:

**Warning:** If you just see "1 3" instead of a fraction, then your browser may not support MathML. Check out the browser compatibility table for further details.

### The display attribute

Note that in the previous example, the formula is on the same line as the text of the paragraph. However, it is quite common to instead render large mathematical formulas centered on their own line as shown below. To achieve that, you need to attach a `display="block"` attribute on the `<math>` element.
```

<!doctype html>
<html lang="en-US">
  <head>
    <title>My first math page</title>
  </head>
  <body>
    <p>
      The fraction
      <math display="block">
        <mfrac>
          <mn>1</mn>
          <mn>3</mn>
        </mfrac>
      </math>
      is not a decimal number.
    </p>
  </body>
</html>
```

You may also notice some subtle change in the appearance: the text and vertical spacing of the fraction becomes a bit bigger. Without the `display="block"` attribute, the height is minimized to avoid disturbing the flow of the surrounding text. With the `display="block"` attribute, priority is instead put on legibility of the mathematical formula.

**Note:** This corresponds to the LaTeX's concept of *inline* formulas (delimited by dollar signs `$...$`) and *display* formulas (delimited by `\[...\]`).

**Note:** The appearance change mentioned above is actually controlled by the `math-style` property which is initially `normal` for `<math display="block">` and `compact` otherwise. In some MathML subtrees, this property can then automatically become `compact` but we will ignore this subtlety for this introductory tutorial. Again, this is similar to LaTeX.

Grouping with the <mrow> element
--------------------------------

The `<math>` element can actually contain an arbitrary number of children and will essentially render them in a row. For instance, the simple formula "1 + 2 + 3" would be encoded like this in MathML:

```html
<math>
  <mn>1</mn>
  <mo>+</mo>
  <mn>2</mn>
  <mo>+</mo>
  <mn>3</mn>
</math>
```

The `<mrow>` element is a generic container that performs similar layout but can be placed anywhere in the MathML subtree. It is helpful to group several elements together. For instance, the numerator of the following fraction (its first child) is "one plus two".

```html
<math>
  <mfrac>
    <mrow>
      <mn>1</mn>
      <mo>+</mo>
      <mn>2</mn>
    </mrow>
    <mn>3</mn>
  </mfrac>
</math>
```

### Active learning: nested expressions

As an exercise, figure out how to write the following expressions using only the MathML elements we've seen so far. If you are stuck or want to verify the solution, check the source code of the example.
```

<ol>
  <li>
    "one half" plus "two third":
    <!-- It's correct but unnecessary to group the children of the math element with an mrow element. -->
    <math>
      <mfrac>
        <mn>1</mn>
        <mn>2</mn>
      </mfrac>
      <mo>+</mo>
      <mfrac>
        <mn>2</mn>
        <mn>3</mn>
      </mfrac>
    </math>
  </li>
  <li>
    "one plus two plus three" over "four plus five":
    <math>
      <mfrac>
        <mrow>
          <mn>1</mn>
          <mo>+</mo>
          <mn>2</mn>
          <mo>+</mo>
          <mn>3</mn>
        </mrow>
        <mrow>
          <mn>4</mn>
          <mo>+</mo>
          <mn>5</mn>
        </mrow>
      </mfrac>
    </math>
  </li>
  <li>
    "one quarter" over "two plus three":
    <math>
      <mfrac>
        <mfrac>
          <mn>1</mn>
          <mn>4</mn>
        </mfrac>
        <mrow>
          <mn>2</mn>
          <mo>+</mo>
          <mn>3</mn>
        </mrow>
      </mfrac>
    </math>
  </li>
</ol>
```

Summary
-------

In this article, we have taken a look at how to use the `<math>` element to insert a mathematical formula inside a HTML document. We have learned about rendering differences between `<math>` elements that use `display="block"` or not. In addition, we stumbled upon a couple of other MathML elements: `<mfrac>` for fractions, `<mrow>` for grouping and finally a few text elements. We will analyze these text containers further in the next article.

* Overview: First steps
* Next
See also
--------

* Using MathML
* The `<math>` element
* The `<mfrac>` element
* The `<mrow>` element
* The `math-style` property
* The `math-depth` property


MathML tables - Learn web development

MathML tables
=============

* Previous
* Overview: First steps
* Next

Once all basic math notations are known, it remains to consider tabular layout which can be used for matrix-like expressions and other advanced math layout.

|  |  |
| --- | --- |
| Prerequisites: | Basic software installed, basic knowledge of
 working with files, and HTML basics (study
 Introduction to HTML. and HTML tables)
  |
| Objective: |
 To get familiar with MathML tabular elements and be aware of some
 use cases.
  |

MathML tabular elements
-----------------------

The MathML tabular elements are similar to the ones for HTML tables: the `<mtable>` element represents a mathematical table, it has `<mtr>` elements as its children (representing rows), each of them having `<mtd>` elements as its children (representing cells). An `<mtable>` element can be inserted anywhere in a MathML formula. The `<mtd>` element can contain any number of MathML children and will lay them out as an `<mrow>` container.

Tables are typically used for matrix-like expressions (including vectors). Here is a basic example taken from the article about the CSS `matrix()` function:
```

<link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
```

```html
<math display="block">
  <mrow>
    <mo>(</mo>
    <mtable>
      <mtr>
        <mtd>
          <mi>a</mi>
        </mtd>
        <mtd>
          <mi>c</mi>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <msub>
            <mi>t</mi>
            <mi>x</mi>
          </msub>
        </mtd>
      </mtr>
      <mtr>
        <mtd>
          <mi>b</mi>
        </mtd>
        <mtd>
          <mi>d</mi>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <msub>
            <mi>t</mi>
            <mi>y</mi>
          </msub>
        </mtd>
      </mtr>
      <mtr>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <mn>1</mn>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
      </mtr>
      <mtr>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <mn>0</mn>
        </mtd>
        <mtd>
          <mn>1</mn>
        </mtd>
      </mtr>
    </mtable>
    <mo>)</mo>
  </mrow>
</math>
```

Allowing cells to span multiple rows and columns
------------------------------------------------

This is again similar to HTML tables. The `<mtd>` element accepts the `columnspan` and `rowspan` attributes to indicate that the cell spans multiples rows and columns. Below the inner matrix spans two columns of the outer matrix:
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My matrix with columnspan</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mrow>
        <mo>(</mo>
        <mtable>
          <mtr>
            <mtd columnspan="2">
              <mrow>
                <mo>(</mo>
                <mtable>
                  <mtr>
                    <mtd>
                      <mi>a</mi>
                    </mtd>
                    <mtd>
                      <mi>c</mi>
                    </mtd>
                  </mtr>
                  <mtr>
                    <mtd>
                      <mi>b</mi>
                    </mtd>
                    <mtd>
                      <mi>d</mi>
                    </mtd>
                  </mtr>
                </mtable>
                <mo>)</mo>
              </mrow>
            </mtd>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mi>T</mi>
            </mtd>
          </mtr>
          <mtr>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mn>1</mn>
            </mtd>
            <mtd>
              <mn>0</mn>
            </mtd>
          </mtr>
          <mtr>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mn>0</mn>
            </mtd>
            <mtd>
              <mn>1</mn>
            </mtd>
          </mtr>
        </mtable>
        <mo>)</mo>
      </mrow>
    </math>
  </body>
</html>
```

**Note:** For historical reason, the MathML attribute for column spanning is called `columnspan` not `colspan`.

Usage for advanced layout
-------------------------

Besides representing matrix-like objects, MathML tables are sometimes used for advanced layout inside mathematical formulas, for example in Wikipedia's definition of Legendre symbol. Here, the different cases are written on three different rows while the values and conditions are placed on two different columns.
```

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>My first matrix</title>
    <link
 rel="stylesheet"
 href="https://fred-wang.github.io/MathFonts/LatinModern/mathfonts.css" />
  </head>
  <body>
    <math display="block">
      <mrow>
        <mrow>
          <mo>(</mo>
          <mfrac>
            <mi>a</mi>
            <mi>b</mi>
          </mfrac>
          <mo>)</mo>
        </mrow>
        <mo>=</mo>
        <mrow>
          <mo>{</mo>
          <mtable>
            <mtr>
              <mtd>
                <mn>1</mn>
              </mtd>
              <mtd>
                <mtext>if </mtext>
                <mi>a</mi>
                <mtext> is a quadratic residue modulo </mtext>
                <mi>p</mi>
                <mtext> and </mtext>
                <mi>a</mi>
                <mtext> is not a multiple of </mtext>
                <mi>p</mi>
                <mo>;</mo>
              </mtd>
            </mtr>
            <mtr>
              <mtd>
                <mo>−</mo>
                <mn>1</mn>
              </mtd>
              <mtd>
                <mtext>if </mtext>
                <mi>a</mi>
                <mtext> is a non-quadratic residue modulo </mtext>
                <mi>p</mi>
                <mo>;</mo>
              </mtd>
            </mtr>
            <mtr>
              <mtd>
                <mn>0</mn>
              </mtd>
              <mtd>
                <mtext>if </mtext>
                <mi>a</mi>
                <mtext> is a multiple of </mtext>
                <mi>p</mi>
                <mo>.</mo>
              </mtd>
            </mtr>
          </mtable>
        </mrow>
      </mrow>
    </math>
  </body>
</html>
```

**Warning:** The `<mtable>` article provides more advanced layout options via special attributes such as alignment or spacing. These originated before CSS equivalents and were originally designed and intended for renderers which were not-CSS aware. However, these attributes may not be implemented in all browsers. In the future, it is likely that usages of `<mtable>` for layout-only purpose (i.e. not actual matrix-like objects) can be replaced with CSS-based alternatives.

Summary
-------

In this article, we've reviewed the `<mtable>`, `<mtr>` and `<mtd>` elements which are the equivalent of HTML elements for tables. We have seen how to use them for representing matrix-like objects and how it is sometimes used for advanced layout.

You've nearly finished this module — we only have one more thing to do. In the three famous mathematical formulas assessment you'll use your new knowledge to rewrite a small mathematical article using HTML and MathML.

* Previous
* Overview: First steps
* Next
See also
--------

* Learning about HTML tables
* The `<mtable>` element
* The `<mtr>` element
* The `<mtd>` element


Properly configuring server MIME types - Learn web development

Properly configuring server MIME types
======================================

MIME types describe the media type of content, either in email, or served by web servers or web applications. They are intended to help provide a hint as to how the content should be processed and displayed.

Examples of MIME types:

* `text/html` for HTML documents.
* `text/plain` for plain text.
* `text/css` for Cascading Style Sheets.
* `text/javascript` for JavaScript files.
* `text/markdown` for Markdown files.
* `application/octet-stream` for binary files where user action is expected.

Server default configurations vary wildly and set different *default* MIME-type values for files with no defined content type.

Versions of the Apache Web Server **before 2.2.7** were configured to report a MIME type of `text/plain` or `application/octet-stream` for unknown content types. Modern versions of Apache report `none` for files with unknown content types.

Nginx will report `text/plain` if you don't define a default content type.

As new content types are invented or added to web servers, web administrators may fail to add the new MIME types to their web server's configuration. This is a major source of problems for users of browsers that respect the MIME types reported by web servers and applications.

Why are correct MIME types important?
-------------------------------------

If a web server or application reports an incorrect MIME type for content (including a "default type" for unknown content), a web browser has no way of knowing the author's intentions. This may cause unexpected behavior.

Some web browsers may try to *guess* the correct MIME type. This allows misconfigured web servers and applications to continue working for those browsers (but not other browsers that correctly implement the standard). Apart from violating the HTTP spec, this is a bad idea for a couple of other significant reasons:

Loss of control

If the browser ignores the reported MIME type, web administrators and authors no longer have control over how their content is to be processed.

For example, a website oriented for web developers might wish to send certain example HTML documents as either `text/html` or `text/plain` in order to have the documents either processed and displayed as HTML or as source code. If the browser guesses the MIME type, this option is no longer available to the author.

Security

Some content types, such as executable programs, are inherently unsafe. For this reason, these MIME types are usually restricted in terms of what actions a web browser will take when given that type of content. An executable program should not be executed on the user's computer and should at least cause a dialog to appear **asking the user** if they wish to download the file.

MIME type guessing has led to security exploits in Internet Explorer that were based upon a malicious author incorrectly reporting a MIME type of a dangerous file as a safe type. This bypassed the normal download dialog, resulting in Internet Explorer guessing that the content was an executable program and then running it on the user's computer.

JavaScript legacy MIME types
----------------------------

When looking for information about JavaScript MIME types, you may see several MIME types that reference JavaScript. Some of these MIME types include:

* `application/javascript`
* `application/ecmascript`
* `application/x-ecmascript`
* `application/x-javascript`
* `text/ecmascript`
* `text/javascript1.0`
* `text/javascript1.1`
* `text/javascript1.2`
* `text/javascript1.3`
* `text/javascript1.4`
* `text/javascript1.5`
* `text/x-ecmascript`
* `text/x-javascript`

While browsers may support any, some, or all of these alternative MIME types, you should **only** use `text/javascript` to indicate the MIME type of JavaScript files.

**Note:** See MIME types (IANA media types) for more information.

How to determine the MIME type to set
-------------------------------------

There are several ways to determine the correct MIME type value to be used to serve your content.

* If your content was created using commercial software, read the vendor's documentation to see what MIME types should be reported for the application.
* Look in IANA's MIME Media Types registry, which contains information on all registered MIME types.
* Search for the file extension in FILExt or the File extensions reference to see what MIME types are associated with that extension. Pay close attention as the application may have multiple MIME types that differ by only one letter.
How to check the MIME type of received content
----------------------------------------------

* In Firefox
    + Load the file and go to **Tools > Page Info** to get the content type for the page you accessed.
    + You can also go to **Tools > Web Developer > Network** and reload the page. The request tab gives you a list of all the resources the page loaded. Clicking on any resource will list all the information available, including the page's `Content-Type` header.
* In Chrome
    + Load the file and go to **View > Developer > Developer Tools** and choose the *Network* tab. Reload the page and select the resource you want to inspect. Under headers look for `Content-Type` and it will report the content type of the resource.
* Look for a `<meta>` element in the page source that gives the MIME type, for example `<meta http-equiv="Content-Type" content="text/html">`.
    + According to the standards, the `<meta>` element that specifies the MIME type should be ignored if there's a Content-Type header available.

IANA keeps a list of registered MIME Media Types. The HTTP specification defines a superset of MIME types, which is used to describe the media types used on the web.

How to set up your server to send the correct MIME types
--------------------------------------------------------

The goal is to configure your server to send the correct `Content-Type` header for each document.

* If you're using the Apache web server, check the ***Media Types and Character Encodings*** section of Apache Configuration: .htaccess for examples of different document types and their corresponding MIME types.
* If you're using Nginx, note that Nginx does not have a `.htaccess` equivalent tool, so all changes will go into the main configuration file.
* If you're using a server-side script or framework to generate content, the way to indicate the content type will depend on the tool you're using. Check the framework or library's documentation.

Regardless of what server system you use, the effect you need to achieve is to set a response header with the name `Content-Type`, followed by a colon and space, followed by a MIME type. High-level environments often allow such headers to be set when generating the page. For example, in a PHP environment, you could set the response header for PDF resources like this:

```php
header('Content-Type: application/pdf')
```

Trying to instead set it with just `header('application/pdf')` won't work.

Related Links
-------------

* IANA | MIME Media Types
* Hypertext Transfer Protocol — HTTP/1.1
* MIME types (IANA media types)
* Apache vs Nginx: Practical Considerations
* Migrate Apache .htaccess to Nginx server block