Subdomain takeovers - Security on the web

Subdomain takeovers
===================

A subdomain takeover occurs when an attacker gains control over a subdomain of a target domain. Typically, this happens when the subdomain has a canonical name (CNAME) in the Domain Name System (DNS), but no host is providing content for it. This can happen because either a virtual host hasn't been published yet or a virtual host has been removed. An attacker can take over that subdomain by providing their own virtual host and then hosting their own content for it.

If an attacker can do this, they can potentially read cookies set from the main domain, perform cross-site scripting, or circumvent content security policies, thereby enabling them to capture protected information (including logins) or send malicious content to unsuspecting users.

A subdomain is like an electrical outlet. If you have your own appliance (host) plugged into it, everything is fine. However, if you remove your appliance from the outlet (or haven't plugged one in yet), someone can plug in a different one. You must cut power at the breaker or fuse box (DNS) to prevent the outlet from being used by someone else.

How do they happen?
-------------------

If the process of provisioning or deprovisioning (removing) a virtual host is not handled properly, there can be an opportunity for an attacker to take over a subdomain.

### During provisioning

An attacker sets up a virtual host for a subdomain name you bought on the hosting provider, before you get to do it.

Suppose you control the domain example.com. You want to add a blog at blog.example.com, and you decide to use a hosting provider who maintains a blogging platform. (For "blog", you can substitute "e-commerce platform", "customer service platform", or any other "cloud-based" virtual hosting scenario.) The process you go through might look like this:

1. You register the name "blog.example.com" with a domain registrar.
2. You set up DNS records to direct browsers that want to access blog.example.com so that they go to the virtual host.
3. You create a virtual host at the hosting provider.

Unless the hosting provider is very careful to verify that the entity who sets up the virtual host actually is the owner of the subdomain name, an attacker who is quicker than you could create a virtual host with the same hosting provider, using your subdomain name. In such a case, as soon as you set up DNS in step 2, the attacker can host content on your subdomain.

### During deprovisioning

You take down your virtual host, but an attacker sets up a new virtual host using the same name and hosting provider.

You (or your company) decide that you no longer want to maintain a blog, so you remove the virtual host from the hosting provider. However, if you don't remove the DNS entry that points to the hosting provider, an attacker can now create their own virtual host with that provider, claim your subdomain, and host their own content under that subdomain.

How can I prevent them?
-----------------------

Preventing subdomain takeovers is a matter of order of operations in lifecycle management for virtual hosts and DNS. Depending on the size of the organization, this may require communication and coordination across multiple departments, which can only increase the likelihood for a vulnerable misconfiguration.

* Define standard processes for provisioning and deprovisioning hosts. Do all steps as closely together as possible.
    + Start provisioning by claiming the virtual host; create DNS records *last*.
    + Start deprovisioning by removing DNS records *first*.
* Create an inventory of all of your organization's domains and their hosting providers, and update it as things change, to ensure that nothing is left dangling.
* Put pressure on hosting vendors to close gaps; ask how they verify that someone claiming a virtual host actually has a legitimate claim to the domain name. Work within your organization to make this part of the vendor qualification process.
My subdomain has been taken over. What should I do?
---------------------------------------------------

If you discover that a subdomain of your domain has been taken over, the first step, if possible, is to "cut power" by removing the DNS entry for the subdomain. If your site has multiple layers of virtualization (e.g., a CDN in addition to virtual hosting), you may need to examine each layer to see where exactly the attacker asserted their virtual host claim to take over your domain.

Learn more
----------

* 'Deep Thoughts' on Subdomain Takeover Vulnerabilities
* Subdomain Takeover: Basics


Mixed content - Security on the web

Mixed content
=============

When a user visits a page served over HTTPS, their connection with the web server is encrypted with TLS and is therefore safeguarded from most sniffers and man-in-the-middle attacks. An HTTPS page that includes content fetched using cleartext HTTP is called a **mixed content** page. Pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-middle attackers. That leaves the pages unsafe.

Types of mixed content
----------------------

There are two categories for mixed content: **mixed passive/display content** and **mixed active content**. The difference lies in the threat level of the worst case scenario if content is rewritten as part of a man-in-the-middle attack. In the case of passive content, the threat is lower (the page may contain misleading content, or the user's cookies may be stolen). In the case of active content, the threat can lead to phishing, sensitive data disclosure, redirection to malicious sites, etc.

### Mixed passive/display content

Mixed passive/display content is content served over HTTP that is included in an HTTPS webpage, but that cannot alter other portions of the webpage. For example, an attacker could replace an image served over HTTP with an inappropriate image or message to the user. The attacker could also infer information about the user's activities by watching which images are served to the user; often images are only served on a specific page within a website. If the attacker observes HTTP requests to certain images, they could determine which webpage the user is visiting.

#### Passive content list

This section lists all types of HTTP requests which are considered passive content:

* `<img>` (`src` attribute)
* `<audio>` (`src` attribute)
* `<video>` (`src` attribute)
* `<object>` subresources (when an `<object>` performs HTTP requests)
### Mixed active content

**Mixed active content** is content that has access to all or parts of the Document Object Model of the HTTPS page. This type of mixed content can alter the behavior of the HTTPS page and potentially steal sensitive data from the user. Hence, in addition to the risks described for mixed display content above, mixed active content is vulnerable to a few other attack vectors.

In the mixed active content case, a man-in-the-middle attacker can intercept the request for the HTTP content. The attacker can also rewrite the response to include malicious JavaScript code. Malicious active content can steal the user's credentials, acquire sensitive data about the user, or attempt to install malware on the user's system (by leveraging vulnerabilities in the browser or its plugins, for example).

The risk involved with mixed content does depend on the type of website the user is visiting and how sensitive the data exposed to that site may be. The webpage may have public data visible to the world or private data visible only when authenticated. If the webpage is public and has no sensitive data about the user, using mixed active content still provides the attacker with the opportunity to redirect the user to other HTTP pages and steal HTTP cookies from those sites.

#### Active content examples

This section lists some types of HTTP requests which are considered active content:

* `<script>` (`src` attribute)
* `<link>` (`href` attribute) (this includes CSS stylesheets)
* `<iframe>` (`src` attribute)
* `fetch()` requests
* `XMLHttpRequest` requests
* All cases in CSS where a `url()` value is used (`@font-face`, `cursor`, `background-image`, and so forth).
* `<object>` (`data` attribute)
* `Navigator.sendBeacon` (`url` attribute)

Other resource types like web fonts and workers may be considered active mixed content, as they are in Chrome.

Loading mixed-content resources
-------------------------------

Most browsers prevent *mixed active content* from loading, and some also block *mixed display content*.

### Loading locally delivered mixed-resources

Browsers *may* allow locally-delivered mixed resources to be loaded. This includes `file:` URLs and content accessed from loopback addresses (e.g. `http://127.0.0.1/`).

* Firefox 55 and later allow loading of mixed content on the loopback address `http://127.0.0.1/` (see Firefox bug 903966),
* Firefox 84 and later allow loading of mixed content on `http://localhost/` and `http://*.localhost/` URLs, as these are now mapped to loopback addresses (see Firefox bug 1220810).
* Chrome also allows mixed content on `http://127.0.0.1/` and `http://localhost/`.
* Safari does not allow any mixed content.
### Upgrading mixed-display resources

Browsers may support automatic upgrade of requests for display/media content from HTTP to HTTPS on secure pages (this prevents mixed-content conditions in which some content is loaded securely while other content is insecure).

Firefox supports this functionality as an experimental feature. It can be enabled using the preference `security.mixed_content.upgrade_display_content`).

* If the upgrade fails (because the media's host doesn't support HTTPS), the media is not loaded.
* Console warnings indicate when content has been successfully upgraded.
* For more information see Experimental features in Firefox > Upgrading mixed display content.
Warnings in Firefox Web Console
-------------------------------

The Firefox Web Console displays a mixed content warning message in the Net pane when a page on your website has this issue. The mixed content resource that was loaded via HTTP will show up in red, along with the text "mixed content", which links to this page.

![Screen shot of the web console displaying a mixed content warning.](/en-US/docs/Web/Security/Mixed_content/mixed_content_-_net_pane.png)

As well as finding these warnings in the Web Console, you could use Content Security Policy (CSP) to report issues. You could also use an online crawler like SSL-check or Missing Padlock that will check your website recursively and find links to insecure content.

Starting in Firefox 23, mixed active content is blocked by default (and mixed display content can be blocked by setting a preference). To make it easier for web developers to find mixed content errors, all blocked mixed content requests are logged to the Security pane of the Web Console, as seen below:

![A screenshot of blocked mixed content errors in the Security Pane of the Web Console](/en-US/docs/Web/Security/Mixed_content/mixed_content_webconsole.png)

To fix this type of error, all requests to HTTP content should be removed and replaced with content served over HTTPS. Some common examples of mixed content include JavaScript files, stylesheets, images, videos, and other media.

**Note:** The console will display a message indicating if mixed-display content is being successfully upgraded from HTTP to HTTPS (instead of a warning about "Loading mixed (insecure) display content").

See also
--------

* Mixed Content - W3C Editor's Draft
* How to fix a website with blocked mixed content


Transport Layer Security - Security on the web

Transport Layer Security
========================

The security of any connection using Transport Layer Security (TLS) is heavily dependent upon the cipher suites and security parameters selected. This article's goal is to help you make these decisions to ensure the confidentiality and integrity of communication between client and server. The Mozilla Operations Security (OpSec) team maintains a wiki entry with reference configurations for servers.

The Transport Layer Security (TLS) protocol is the standard for enabling two networked applications or devices to exchange information privately and robustly. Applications that use TLS can choose their security parameters, which can have a substantial impact on the security and reliability of data. This article provides an overview of TLS and the kinds of decisions you need to make when securing your content.

History
-------

When HTTPS was introduced, it was based on Secure Sockets Layer (SSL) 2.0, a technology introduced by Netscape. It was updated to SSL 3.0 not long after, and as its usage expanded, it became clear that a common, standard encryption technology needed to be specified to ensure interoperability among all web browsers and servers. The Internet Engineering Task Force (IETF) specified TLS 1.0 in RFC 2246 in January 1999. The current version of TLS is 1.3 (RFC 8446).

Despite the fact that the web now uses TLS for encryption, many people still refer to it as "SSL" out of habit.

Although TLS can be used on top of any low-level transport protocol, the original goal of the protocol was to encrypt HTTP traffic. HTTP encrypted using TLS is commonly referred to as HTTPS. TLS-encrypted web traffic is by convention exchanged on port 443 by default, while unencrypted HTTP uses port 80 by default. HTTPS remains an important use case for TLS.

HTTP over TLS
-------------

TLS provides three primary services that help ensure the safety and security of data exchanged with it:

Authentication

Authentication lets each party to the communication verify that the other party is who they claim to be.

Encryption

Data is encrypted while being transmitted between the user agent and the server, in order to prevent it from being read and interpreted by unauthorized parties.

Integrity

TLS ensures that between encrypting, transmitting, and decrypting the data, no information is lost, damaged, tampered with, or falsified.

A TLS connection starts with a handshake phase where a client and server agree on a shared secret and important parameters, like cipher suites, are negotiated. Once parameters and a data exchange mode where application data, such HTTP, is exchanged.

### Cipher suites

The primary parameters that the TLS handshake negotiates is a cipher suite.

In TLS 1.2 and earlier, the negotiated cipher suite includes a set of cryptographic algorithms that together provide the negotiation of the shared secret, the means by which a server is authenticated, and the method that will be used to encrypt data.

The cipher suite in TLS 1.3 primarily governs the encryption of data, separate negotiation methods are used for key agreement and authentication.

Different software might use different names for the same cipher suites. For instance, the names used in OpenSSL and GnuTLS differ from those in the TLS standards. The cipher names correspondence table on the Mozilla OpSec team's article on TLS configurations lists these names as well as information about compatibility and security levels.

### Configuring your server

Correctly configuring your server is crucial. In general, you should try to limit cipher support to the newest ciphers possible which are compatible with the browsers you want to be able to connect to your site. The Mozilla OpSec guide to TLS configurations provides more information on recommended configurations.

To assist you in configuring your site, Mozilla provides a helpful TLS configuration generator that will generate configuration files for the following Web servers:

* Apache
* Nginx
* Lighttpd
* HAProxy
* Amazon Web Services CloudFormation Elastic Load Balancer

Using the configurator is a recommended way to create the configuration to meet your needs; then copy and paste it into the appropriate file on your server and restart the server to pick up the changes. The configuration file may need some adjustments to include custom settings, so be sure to review the generated configuration before using it; installing the configuration file without ensuring any references to domain names and the like are correct will result in a server that just doesn't work.

TLS 1.3
-------

RFC 8446: TLS 1.3 is a major revision to TLS. TLS 1.3 includes numerous changes that improve security and performance. The goals of TLS 1.3 are:

* Remove unused and unsafe features of TLS 1.2.
* Include strong security analysis in the design.
* Improve privacy by encrypting more of the protocol.
* Reduce the time needed to complete a handshake.

TLS 1.3 changes much of the protocol fundamentals, but preserves almost all of the basic capabilities of previous TLS versions. For the web, TLS 1.3 can be enabled without affecting compatibility with some rare exceptions (see below).

The major changes in TLS 1.3 are:

* The TLS 1.3 handshake completes in one round trip in most cases, reducing handshake latency.
* A server can enable a 0-RTT (zero round trip time) handshake. Clients that reconnect to the server can send requests immediately, eliminating the latency of the TLS handshake entirely. Though the performance gains from 0-RTT can be significant, they come with some risk of replay attack, so some care is needed before enabling this feature.
* TLS 1.3 supports forward-secure modes only, unless the connection is resumed or it uses a pre-shared key.
* TLS 1.3 defines a new set of cipher suites that are exclusive to TLS 1.3. These cipher suites all use modern Authenticated Encryption with Associated Data (AEAD) algorithms.
* The TLS 1.3 handshake is encrypted, except for the messages that are necessary to establish a shared secret. In particular, this means that server and client certificates are encrypted. Note however that the server identity (the server\_name or SNI extension) that a client sends to the server is not encrypted.
* Numerous mechanisms have been disabled: renegotiation, generic data compression, Digital Signature Algorithm (DSA) certificates, static RSA key exchange, and key exchange with custom Diffie-Hellman (DH) groups.

Implementations of draft versions of TLS 1.3 are available. TLS 1.3 is enabled in some browsers, including the 0-RTT mode. Web servers that enable TLS 1.3 might need to adjust configuration to allow TLS 1.3 to operate successfully.

TLS 1.3 adds just one significant new use case. The 0-RTT handshake can provide significant performance gains for latency sensitive applications, like the web. Enabling 0-RTT requires additional steps, both to ensure successful deployment and to manage the risks of replay attacks.

The removal of renegotiation in TLS 1.3 might affect some web servers that rely on client authentication using certificates. Some web servers use renegotiation to either ensure that client certificates are encrypted, or to request client certificates only when certain resources are requested. For the privacy of client certificates, the encryption of the TLS 1.3 handshake ensures that client certificates are encrypted; however this might require some software changes. Reactive client authentication using certificates is supported by TLS 1.3 but not widely implemented. Alternative mechanisms are in the process of being developed, which will also support HTTP/2.

Retiring old TLS versions
-------------------------

To help with working towards a more modern, more secure web, all major browsers began removing support for TLS 1.0 and 1.1 in early 2020. You'll need to make sure your web server supports TLS 1.2 or 1.3 going forward.

From version 74 onwards, Firefox will return a Secure Connection Failed error when connecting to servers using the older TLS versions (Firefox bug 1606734).

TLS handshake timeout values
----------------------------

If the TLS handshake starts to become slow or unresponsive for some reason, the user's experience can be affected significantly. To mitigate this problem, modern browsers have implemented handshake timeouts:

* Since version 58, Firefox implements a TLS handshake timeout with a default value of 30 seconds. The timeout value can be varied by editing the `network.http.tls-handshake-timeout` pref in about:config.
See also
--------

* The Mozilla SSL Configuration Generator and Cipherlist.eu can help you generate configuration files for your server to secure your site.
* The Mozilla Operations Security (OpSec) team maintains a wiki page with reference TLS configurations.
* Mozilla Observatory, SSL Labs, and Cipherscan can help you test a site to see how secure its TLS configuration is.
* Secure Contexts
* Strict-Transport-Security HTTP header


Secure contexts - Security on the web

Secure contexts
===============

A **secure context** is a `Window` or `Worker` for which certain minimum standards of authentication and confidentiality are met. Many Web APIs and features are accessible only in a secure context. The primary goal of secure contexts is to prevent MITM attackers from accessing powerful APIs that could further compromise the victim of an attack.

Why should some features be restricted?
---------------------------------------

Some APIs on the web are very powerful, giving an attacker the ability to do the following and more:

* Invade a user's privacy.
* Get low-level access to a user's computer.
* Get access to data such as user credentials.
When is a context considered secure?
------------------------------------

A context is considered secure when it meets certain minimum standards of authentication and confidentiality defined in the Secure Contexts specification. A particular document is considered to be in a secure context when it is the active document of a top-level browsing context (basically, a containing window or tab) that is a secure context.

For example, even for a document delivered over TLS within an `<iframe>`, its context is **not** considered secure if it has an ancestor that was not also delivered over TLS.

However, it's important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure. That's because the determination of whether a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated — and not whether a non-secure context happened to be used to create it.

Locally-delivered resources such as those with `http://127.0.0.1` URLs, `http://localhost` and `http://*.localhost` URLs (e.g. `http://dev.whatever.localhost/`), and `file://` URLs are also considered to have been delivered securely.

**Note:** Firefox 84 and later support `http://localhost` and `http://*.localhost` URLs as trustworthy origins (earlier versions did not, because `localhost` was not guaranteed to map to a local/loopback address).

Resources that are not local, to be considered secure, must meet the following criteria:

* must be served over `https://` or `wss://` URLs
* the security properties of the network channel used to deliver the resource must not be considered deprecated
Feature detection
-----------------

Pages can use feature detection to check whether they are in a secure context or not by using the `isSecureContext` boolean, which is exposed on the global scope.

```js
if (window.isSecureContext) {
  // Page is a secure context so service workers are now available
  navigator.serviceWorker.register("/offline-worker.js").then(() => {
    // …
  });
}
```

Specifications
--------------

| Specification |
| --- |
| Secure Contexts  |

See also
--------

* Platform features restricted to secure contexts — a list of the features available only in secure contexts
* `isSecureContext`
* https://permission.site — A site that allows you to check what API permission checks your browser employs, over HTTP and HTTPS
* Strict-Transport-Security HTTP header


Features gated by user activation - Security on the web

Features gated by user activation
=================================

To ensure applications are unable to abuse APIs that can create a bad user experience when the behavior is not desired, some APIs can only be used when the user is in an "active interaction" state, meaning the user is currently interacting with the web page, or has interacted with the page at least once. Browsers limit access to sensitive APIs like popups, fullscreen, or vibration APIs to active user interactions to prevent malicious scripts from abusing these features. This page lists web platform features available only after user activation.

A user activation either implies that the user is currently interacting with the page, or has completed an interaction since page load. Typically, this is a click on a button or some other user interaction with the UI.

More precisely, an *activation triggering input event* is an event which:

* has the `isTrusted` attribute set to `true`, and
* is an event of the following types:
    + `keydown` (except for the `Esc` key nor a shortcut key reserved by the user agent)
    + `mousedown`
    + `pointerdown` (if `pointerType` is "mouse")
    + `pointerup` (if `pointerType` is not "mouse")
    + `touchend`

If an activation has been triggered, the user agent differentiates between two types of user activation window states: sticky and transient.

Transient activation
--------------------

Transient activation is a window state that indicates a user has recently pressed a button, moved a mouse, used a menu, or performed some other user interaction. Transient activation expires after a timeout (if not renewed by further interaction) and may also be consumed by some APIs (like `Window.open()`).

APIs that require transient activation (list is not exhaustive):

* `beforeunload` event
* `Clients.openWindow()`
* `Clipboard.read()`
* `Clipboard.readText()`
* `Clipboard.write()`
* `Clipboard.writeText()`
* `ContactsManager.select()`
* `Document.requestStorageAccess()`
* `DocumentPictureInPicture.requestWindow()`
* `Element.requestFullScreen()`
* `Element.requestPointerLock()`
* `EyeDropper.open()`
* `GPUAdapter.requestAdapterInfo()`
* `HID.requestDevice()`
* `HTMLInputElement.showPicker()`
* `HTMLSelectElement.showPicker()`
* `HTMLVideoElement.requestPictureInPicture()`
* `IdleDetector.requestPermission()`
* `Keyboard.lock()`
* `MediaDevices.getDisplayMedia()`
* `MediaDevices.getViewportMedia()`
* `MediaDevices.selectAudioOutput()`
* `MediaStreamTrack.sendCaptureAction()`
* `Navigator.share()`
* `PaymentRequest.show()`
* `PresentationRequest.start()`
* `RemotePlayback.prompt()`
* `Serial.requestPort()`
* `USB.requestDevice()`
* `Keyboard.lock()`
* `Window.getScreenDetails()`
* `Window.open()`
* `Window.queryLocalFonts()`
* `Window.showOpenFilePicker()`
* `Window.showSaveFilePicker()`
* `Window.showDirectoryPicker()`
* `WindowClient.focus()`
* `XRSystem.requestSession()`
Sticky activation
-----------------

Sticky activation is a window state that indicates a user has pressed a button, moved a mouse, used a menu, or performed some other user interaction. It is not reset after it has been set initially (unlike transient activation).

APIs that require sticky activation (not exhaustive):

* `Navigator.vibrate()`
* `VirtualKeyboard.show()`
* Autoplay of Media and Web Audio APIs (in particular for `AudioContexts`).
UserActivation API
------------------

To programmatically determine if a window has either sticky or transient user activation, the `UserActivation` API provides two properties which are available using `navigator.userActivation`:

* `UserActivation.hasBeenActive` indicates whether the window has sticky user activation.
* `UserActivation.isActive` indicates whether the window has transient user activation.
See also
--------

* Transient activation
* Sticky activation
* `UserActivation` API
* Features restricted to secure contexts


How to fix a website with blocked mixed content - Security on the web

How to fix a website with blocked mixed content
===============================================

Starting with Firefox 23, Firefox blocks active mixed content by default. This follows a practice adopted by Chrome.

This page explains what you should be aware of as a web developer.

Your website may break
----------------------

If your website delivers HTTPS pages, all active mixed content delivered via HTTP on this pages will be blocked by default. Consequently, your website may appear broken to users (if iframes or plugins don't load, etc.). Passive mixed content is displayed by default, but users can set a preference to block this type of content, as well.

Note that since mixed content blocking already happens in Chrome, it is very likely that if your website works in Chrome, it will work equally well in Firefox with mixed content blocking.

In any case, the best way to know if something is broken in Firefox is to download the latest Firefox Edition, open different pages on your website with the web console open (enable the "Security" messages) and see if anything related to mixed content is reported. Or use a free online crawler like SSL-check or Missing Padlock, a desktop crawler like HTTPSChecker, or a CLI tool like mcdetect to check your website recursively and find links to insecure content. If nothing is said about mixed content, your website is in good shape: Keep making excellent websites!

How to fix your website
-----------------------

The best strategy to avoid mixed content blocking is to serve all the content as HTTPS instead of HTTP.

**For your own domain,** serve all content as HTTPS and fix your links. Often, the HTTPS version of the content already exists and this just requires adding an "s" to links - http:// to https://.

However, in some cases, the path may just be incorrect to the media in question. There are online as well as offline tools (depending on your operating system) such as linkchecker to help resolve this.

**For other domains,** use the site's HTTPS version if available. If HTTPS is not available, you can try contacting the domain and asking them if they can make the content available via HTTPS.


How to turn off form autocompletion - Security on the web

How to turn off form autocompletion
===================================

This article explains how a website can disable autocomplete for form fields.

By default, browsers remember information that the user submits through `<input>` fields on websites. This enables the browser to offer autocompletion (that is, suggest possible completions for fields that the user has started typing in) or autofill (that is, pre-populate certain fields upon load).

These features are usually enabled by default, but they can be a privacy concern for users, so browsers can let users disable them. However, some data submitted in forms either are not useful in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code). As website author, you might prefer that the browser not remember the values for such fields, even if the browser's autocomplete feature is enabled.

Note that the WCAG 2.1 Success Criterion 1.3.5: Identify Input Purpose does not require that autocomplete/autofill actually work - merely that form fields that relate to specific personal user information are programmatically identified. This means that the criterion can be passed (by adding the relevant `autocomplete` attributes to individual form fields) even when autocompletion for the form itself has been turned off.

Disabling autocompletion
------------------------

To disable autocompletion in forms, you can set the `autocomplete` attribute to "off":
```

autocomplete="off"
```

You can do this either for an entire form, or for specific input elements in a form:

```html
<form method="post" action="/form" autocomplete="off">
  …
</form>
```

```html
<form method="post" action="/form">
  …
  <div>
    <label for="cc">Credit card:</label>
    <input type="text" id="cc" name="cc" autocomplete="off" />
  </div>
</form>
```

Setting `autocomplete="off"` on fields has two effects:

* It tells the browser not to save data inputted by the user for later autocompletion on similar forms, though heuristics for complying vary by browser.
* It stops the browser from caching form data in the session history. When form data is cached in session history, the information filled in by the user is shown in the case where the user has submitted the form and clicked the Back button to go back to the original form page.

If a browser keeps on making suggestions even after setting autocomplete to off, then you have to change the name attribute of the input element.

The autocomplete attribute and login fields
-------------------------------------------

Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.

Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.

Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.

For this reason, many modern browsers do not support `autocomplete="off"` for login fields:

* If a site sets `autocomplete="off"` for a `<form>`, and the form includes username and password input fields, then the browser still offers to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.
* If a site sets `autocomplete="off"` for username and password `<input>` fields, then the browser still offers to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.
### Preventing autofilling with autocomplete="new-password"

If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use `autocomplete="new-password"`.

This is a hint, which browsers are not required to comply with. However modern browsers have stopped autofilling `<input>` elements with `autocomplete="new-password"` for this very reason. For example, Firefox version 67 (see Firefox bug 1119063) stopped autofilling in this case; however, Firefox 70 (see Firefox bug 1565407) can suggest securely-generated passwords, but does not autofill a saved password. See the `autocomplete` compat table for more details.


Features restricted to secure contexts - Security on the web

Features restricted to secure contexts
======================================

This reference lists the web platform features available only in secure contexts — see Secure Contexts for a definition and more details.

Current features available only in secure contexts
--------------------------------------------------

This section lists APIs that specifications make available only in secure contexts.

* Async Clipboard API
* Audio Output Devices API
* Background Fetch API
* Background Synchronization API
* Badging API
* Barcode Detection API
* Battery Status API
* `Cache-Control: immutable`
* Contact Picker API
* Content Index API
* Cookie Store API
* Credential Management API
* Device Memory API
* Device Orientation / Device Motion
* Document Picture-in-Picture API
* EyeDropper API
* Encrypted Media Extensions
* File System API
* Generic Sensor API
* Gamepad API
* Geolocation API
* Idle Detection API
* Keyboard API
* Local Font Access API
* Notifications API
* Payment Handler API
* Payment Request API
* Presentation API
* Push API
* Reporting API
* Screen Capture API
* Screen Wake Lock API
* Service Workers
* Shared Storage API
* Storage API
* VirtualKeyboard API
* Web Authentication API
* Web Bluetooth
* Web Locks API
* Web MIDI
* Web NFC API
* Web Crypto API
* WebCodecs API
* WebGPU API
* WebHID API
* WebOTP API
* WebTransport API
* WebUSB API
* WebXR Device API
* Web Share API
* Window Management API

In addition, the following methods require a secure context (even if the associated API does not):

* `MediaDevices.getUserMedia()`
* `Navigator.registerProtocolHandler()`
See also
--------

* Secure contexts
* "secure context" query on Chrome Platform Status


Accessibility and Spacial Patterns - Accessibility

Accessibility and Spacial Patterns
==================================

### Spatial Localization

NASA conducted research on the perception of color, and found that luminance contrast mattered greatly as to how colors are perceived. The two images below are from NASA research, specifically, from the article, "Designing With Blue"

![Comparison of the stability of the spatial localization of yellow vs. red. Both are roughly isoluminant with their backgrounds. The misalignment and gap between the chromatic bars and black bars is physically the same for the yellow and red but much less visually obvious for the yellow.](/en-US/docs/Web/Accessibility/Accessibility_and_Spacial_Patterns/yellow_edge_3.gif)
![Comparison of the stability of the spatial localization of yellow vs. red. Both are roughly isoluminant with their backgrounds. The misalignment and gap between the chromatic bars and black bars is physically the same for the yellow and red but much less visually obvious for the yellow.](/en-US/docs/Web/Accessibility/Accessibility_and_Spacial_Patterns/yellow_edge_4.gif)

"***Spatial Localization.** Symbols which have the same luminance as their background are perceptually less securely located in space and time than are symbols with higher luminance contrast. They tend to "float" visually or be "captured" by adjacent symbols with high luminance-contrast. The phenomenon seems to be especially problematic for symbol/background combinations that differ only in the blue channel.*"

### Distance between stripes

Photosensitive seizures may be caused by static images as well as animation. The mechanism for this is poorly understood, but is believed to be linked to "gamma oscillations" set up in the brain. These oscillations in the brain are a different kind of response than other kinds of neurological responses believed to cause photosensitive seizures.

Stripes and patterns are typical of the kinds of images that create problems, and stripes have been studied most closely. There's the potential for causing harm if there are more than five light-dark pairs of stripes in any orientation. They can be parallel, radial, curved or straight, and may be formed by rows of repeating elements.

In 2005, Arnold Wilkins, John Emmett, and Graham Harding evaluated the guidelines for characterizing patterned images that could precipitate seizures. They revised the guidelines to their fundamental core, and came up with a surprisingly simple, but powerful test. which they published in the paper, **Characterizing the Patterned Images That Precipitate Seizures and Optimizing Guidelines To Prevent Them**

**Note:** The steps necessary to evaluate material reduce to the following:

Look at the screen:

* Are there more than five stripes?
* If so, do they last longer than 0.5 s?
* If so, does the brightness exceed the stated limit?
* If so, categorize the motion of the pattern.
* Are the guidelines contravened?

If so, reduce brightness.

### Text and padding

WCAG standards for contrast perception do not take into account the effect of padding. For example, blue text on a gray background is easier to perceive if it is surrounded "locally" by black than by white. There is such a thing as "local" adaptation to colors. The bottom line: padding matters.

### Math

Spatial reasoning affects Math learning; consequently, spatial relationships in how math is presented affects cognition. The web developer can do something about this in the manner in which they display math. Animation figures strongly in this arena. For example, "how" an object looks when it is rotated, from different angles, how they look sliced, and how they relate to each other in space all make a difference in an ability to understand Math in spatial terms.

### Braille

Modern technology enables non-experts to print Braille. Adobe Illustrator, for example, allows one to Typeset ADA Braille for printing out.

The ability to represent spatial patterns accurate to those who are blind is critical for accessibility. For example, knowing Braille is not enough. The Braille dots have to be spatially apart from one another so as to be readable in a "human" way. The human touch does distinguish with ease braille dots that are too close or too far apart from one another.

Space has to surround the braille character. A user of braille does not lay a finger on "top" of a braille character, the user has to move her finger over the character, in the way that a sighted person must move her eyes across text written on a page.

The nature of space can change depending upon what MIME type is being used, and its version. For example, borders on SVG can extend both inward and outward from its dimensions, or for newer versions of SVG, entirely outward from it, thus reducing the space around the SVG to enable perception.

See Also
--------

### MDN

* Accessibility: What users can do to browse more safely
* Web accessibility for seizures and physical reactions
* Web Accessibility: Understanding Colors and Luminance
### Braille

* Part 3: A Step-by-Step Guide to Typesetting ADA Braille Correctly in Adobe Illustrator
* Spatial Math in BrailleBlaster (4 of 5)
### Government Literature

* NASA: Designing With Blue
### Math

* Spatial Reasoning: Why Math Talk is About More Than Numbers
### Scientific Literature

* Color constancy in context: Roles for local adaptation and levels of reference
* Gamma oscillations and photosensitive epilepsy
* Characterizing the Patterned Images That Precipitate Seizures and Optimizing Guidelines To Prevent Them Arnold Wilkins, John Emmett, and Graham Harding

#### Contributors

Heartfelt thanks to Jim Allan of the Diagram Center for his discussions on the topic of alternative means of education.


Accessibility information for web authors - Accessibility

Accessibility information for web authors
=========================================

Guidelines and Regulations
--------------------------

1. ARIA Authoring Practices Guide (APG)
 Guide to accessibility semantics defined by the Accessible Rich Internet Application (ARIA) specification to create accessible web experiences. Describes how to apply accessibility semantics to common design patterns and widgets, providing design patterns and functional examples.
2. Web Content Accessibility Guidelines (WCAG)
 Another important set of guidelines from the W3C *Web Accessibility Initiative (WAI)*. The European Union is looking to base their upcoming accessibility regulations on these guidelines. These guidelines are discussed on the WAI interest group discussion list.
3. ARIA on this site
MDN guide to all the ARIA roles and ARIA properties, including best practices, related roles and properties, and examples.
How-to's
--------

1. Accessibility for frontend developers
 A brief guide from the U.S. General Services administration's Technology Transformation Services covering several accessibility topics with links to "how-to" videos and to related WCAG references.
2. Accessible Web Page Authoring
 IBM has made their accessibility requirements that need to be met public and interactive.
### Automated Checking & Repair

Use a tool to quickly check for common errors in your browser.

* HTML CodeSniffer
* aXe
* Lighthouse Accessibility Audit
* Accessibility Insights
* WAVE

Tools to integrate into your build process, programmatically adding accessibility tests, so you can catch errors as you develop your web application:

* axe-core
* jsx-a11y
* Lighthouse Audits
* AccessLint.js

Continuous integration tools to find accessibility issues in your GitHub pull requests:

* AccessLint

While best to test your web applications with real users, you can simulate color blindness, low vision, low and contrast, and zooming. You should always test your site with out a mouse and touch to test keyboard navigation. You may also want to try your site using voice commands. Try disabling your mouse and using browser extensions like Web Disability Simulator


Web Accessibility: Understanding Colors and Luminance - Accessibility

Web Accessibility: Understanding Colors and Luminance
=====================================================

While understanding color, luminance, and saturation is important for design and readability for all sighted users, they are essential for those with reduced vision and color-deficient vision and those with specific neurological, cognitive, and other impairments.

Accessibility guidelines define adequate color contrast for sighted users with reduced vision, as well as guidelines intended to help users with color insensitive vision, commonly referred to as "color blindness". Understanding color is also important in preventing seizures and other physical reactions in people with vestibular disorders or other neurological disorders.

Overview
--------

The choice of colors and their use is a significant component of accessibility. On the surface, the subject seems simple. Still, it is a complex subject because color perception is as much about the physiology of the eye and human brain processing as it is about light emitting from a computer screen.

### Environment and perception

Environment matters. Perception of color in a well-lit room will be different than perception of that same color on that same computer screen in a dark room. Regarding accessibility, using certain color combinations has more impact than others. Font size, font style (some fonts are so thin or fancy that they present accessibility problems on their own), background color, the size of the background space around the text, even pixel densities, and more all affect how color is delivered from the screen.

A viewer's distance from the screen, the ambient background, the health of his eyes, and more all affect how that color is received by the viewer. How the viewer perceives color after it gets to their eyes is yet another matter, and can be affected by overall health. Fortunately, there are media queries that enable developers to provide styles based on user preferences, including contrast and color scheme preferences.

When supported, the Ambient Light Sensor interface returns the current light level or illuminance of the ambient light around the hosting device, enabling a web page to be aware of any change in the light intensity, and consequently, adjust the text accordingly. Additionally, the above media queries enable developers to provide alternative user experiences when user preferences indicate preferred contrast levels, automatically adjusting levels depending on the user's location and what kind of screen they are using.

### Luminance and perception

Color, contrast, and luminance are the most central and critical concepts to creating accessible web content with color. Luminance is of particular importance, however, because understanding what it is and how it is employed enables accessibility for those who are color-blind, as well as those who can perceive color. The luminance contrast enables the color blind to distinguish dark from light.

Luminance must be established before the contrast may be. When speaking of color contrast, W3C formulas are incorporating luminance, not just the colors ("hues") themselves.

### Terminology

Terminology can be confusing because different terms often describe the same thing. "Luminance" and "Saturation" are particularly important to get right. For example, "saturation" is known as "chroma" in some circles. In others, "chroma" and "saturation" are two different concepts. The "L" in the HSL color space is sometimes referred to as "luminosity," and other times as "lightness." Even something seemingly simple, like naming common colors, can be open to debate. For example, the color "crimson red" may be described in hex values as `#990000` by some and `#DC143C` by others. For this document, we'll use terminology as it is defined in the W3C, in the CSS Color Module Level 4

When working with color, it's important to know which "color space" you are working in, as different color spaces map to different measurement systems.

In color printing, your printer likely has cyan, magenta, yellow, and black (CMYK) ink cartridges. CMYK is a subtractive model wherein the four inks *remove* specific wavelengths of light, reflecting only the narrow range each is associated with. RGB is an additive color model that adds different proportions of red, green, and blue lights.

Currently, the RGB color space predominates as the space web developers work in. While HEX, RGB, and HSL color spaces are notated differently, browsers automatically convert values between these color notations. CSS color modules provide additional color spaces. Still, because of the current domination of the RGB color space in measuring color output, most calculations in this document are presumed to be in the RGB color space and, very specifically, in the sRGB color space.

The sRGB color space
--------------------

Color has many ways of being defined, as is apparent in the `<color>` data type, including RGB, RGB decimal, RGB percent, HSL, HWB, LCH, and CMYK, among others.

For digital concerns, much of the technology has historically resided in the RGB color space. The RGB color model is extended to include "alpha" — RGBA — to allow specification of the opacity of a color. Other methods for measuring color involve measurements using other color spaces and are supported in modern displays and browsers. Still, color measurements in the RGB color space predominate, including in video production.

Technologies, such as OpenGL and Direct3D incorporate support for the sRGB gamma curve, although some articles for OpenGL reference use of RGBA rather than sRGB. WebGL is usually in the RGBA format; see an example of how it is used in "Clearing with colors".

### CSS color values

It's important to know that there are variations even within one color space, such as the RGB color space. For example, variations of the RGB color space include **RGB**, **sRGB**, **Adobe RGB**, **Adobe Wide Gamut RGB**, and **RGBA**, among others.

These are examples of the CSS notations used to define a color. Here the example color for each is a fully opaque magenta:

```css
/\* named color \*/
color: magenta;

/\* sRGB value with percentage values \*/
color: rgb(100% 0% 100%);
color: rgb(100% 0% 100% / 100%);

/\* by sRGB numeric values \*/
color: rgb(255 0 255);
color: rgb(255 0 255 / 1);

/\* legacy rgba notation \*/
color: rgba(100%, 0%, 100%, 100%);
color: rgba(255, 0, 255, 1);

/\* by sRGB value in hex \*/
color: #f0f; /\* #rgb, a shorthand for #rrggbb \*/
color: #ff00ff; /\* #rrggbb \*/
color: #f0ff; /\* #rgba \*/
color: #ff00ffff; /\* #rrggbbaa \*/

/\* by HSL representation of the sRGB value \*/
color: hsl(300 100% 50%);
color: hsl(300deg 100% 50% / 100%);

/\* by HWB representation of the sRGB value \*/
color: hwb(300deg 0% 0%);
color: hwb(300 0% 0% / 1);
```

The first example uses one of the defined named colors.

We can set the sRGB values directly as a percentage, with 0% being off (black) and 100% being the full value for that color. The values are in the order of red, green, and blue. We can also set the sRGB values directly by a number from 0 to 255.

Shown after that are hex color values. Hexadecimal is a numbering system with base-16, where the 0-255 integer is represented by two digits ranging from 0-15 using the digits 0-9 and a-f for 10-15. Thus, `ff` = `255`, `00` = `0`, and `d5` = `200`. The '#' symbol precedes the color to indicate the value is hex.

If all values are pairs of identical digits, the value can be represented by single digits that the browser will duplicate. Thus `f00` is the same as `ff0000`. If a fourth set of numbers is present, that value is the A in RGBA, the alpha channel defining transparency in terms of the opacity value of the color. A higher value means the color is more opaque and therefore, less transparent. In the examples above, the alpha value is `f`, `ff`, `1`, and `100%` for fully opaque.

The examples also show the legacy `rgba()` syntax. The older syntax for color functions was comma-separated, with separate functions for when the alpha channel was included. New color functions only have one syntax with space-separated (rather than comma-separated) values, with the alpha channel, if present, being preceded by a slash.

The following examples show "HSL", which stands for *Hue, Saturation, and Lightness*. HSL color values are considered by many to be more intuitive than RGB values. The color produced from the settings are still in the sRGB colorspace, but `hsl()` is an intuitive syntax for many. The hue is adjusted as an angle, and it is easy to create a user interface using a knob or circular control to adjust the hue. Do note that HSL colors incorporate *lightness*, not *luminance*, which is a significant consideration.

The last examples shows "HWB" which stands for *Hue, Whiteness, and Blackness*. Unlike `rgba()` and `hsla()`, `hwb()` does not have a legacy `a` syntax and does not support comma-separated values. With both `hsl()` and `hwb()` the first value can be a `<number>` or an `<angle>` value. When unitless, the value is interpreted as `deg` degrees.

### Conversions

As we saw, one color within the same color space may be expressed in many ways. Looking at how the RGB color space is used to describe the color "magenta", you can see that the same color may be expressed in a shorthand, three-digit hex number that converts to an rgb value as a six-digit hex number that also converts to the same rgb value, or as a rgba value, expressed in percentages.

RGB is hardware-oriented, reflecting the use of CRTs. Many developers and designers prefer the intuitiveness of `hsl()` notation. Converting from RGB to HSL is not a simple equation. Fortunately, browsers do it automatically, and shift-clicking on colors in browser developer tools provides conversion functionality.

In addition to developer tools, many tools can convert RGB to HSL for you and provide both the RGB hexadecimal and CSS function syntax. A great example of a tool that converts colors for you is Tom Jewett's "mini color selector" with HSL, RGB, and Hex options for checking contrast in the browser. Note that developer tools color pickers and this tool all provide WCAG color contrast values.

![Color picker with HSL and RGB, with color contrast values.](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance/microcolorsc.jpg)

As noted earlier, the CSS color module includes adding additional colorspaces, including `lch()` functional color notation and the `lab()` color coordinate system which can specify any visible color, but because of its ubiquity, sRGB is the default and preferred colorspace for accessibility.

Where accessibility is concerned, however, standards and guidelines are currently written predominantly using the sRGB color space, especially as it applies to color contrast ratios.

**Note:** Almost all systems used today to view Web content assume sRGB encoding. Unless it is known that another color space will be used to process and display the content, authors should evaluate using sRGB colorspace. If using other color spaces, apply the principles of minimum contrast ratios.

CSS Color Module Level 5 introduced `lch()` functional color notation and the `lab()` color coordinate system which can specify any visible color. These will change the domination of the sRGB color space in the future, but we are not there yet.

### Querying color values

The `Window.getComputedStyle()` method returns values using the RGB Decimal Reference scale. For example, calling `Window.getComputedStyle()` on a div with a `background-color: #990000;` set returns the computed background color as `rgb(153 0 0)` — the RGB Decimal reference. Being tied to computer hardware,`Window.getComputedStyle()` measures color in terms of RGB, not how the human eye perceives color.

### Red / green color blindness

Protanopia is a color vision deficiency in which the eye has no red cones; sRGB can still be perceived via green cones, though darker than normal vision. Both protan (red deficient) and deutan (green deficient) deficiencies cause difficulty distinguishing *between* red and green.

Developer tools can help simulate color vision differences right in your browser. For example, Firefox's Accessibility Inspector enables simulating protanopia, deuteranopia, tritanopia, achromatopsia, and contrast loss right in the accessibility panel.

![Snippet of Firefox developer tools showing the simulate popup](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance/simulate_color_differences.jpg)

Luminance and Contrast
----------------------

### Contrast

The contrast between colors ("hues") is a critical component, but the use of color ("hues") alone is not enough to create accessible content. As mentioned before, any calculation of contrast must include luminance.

In addition, the "shape" of the text itself will matter. Thin letters will be harder to read than thick ones; all typefaces need space to "breathe" for human perception.

### Contrast and font size

WCAG contrast guidelines define "large" text as text that is `18pt` (approximately `24px`) or larger when `font-weight` is `normal` and `14pt` (approximately `18.7px`) for `bold` text. Stating:

*Text that is larger and has wider character strokes is easier to read at lower contrast. Therefore, the contrast requirement for larger text is lower. This allows authors to use a wider range of color choices for large text, which is helpful for the design of pages, particularly titles.*

While larger text does not require as great color contrast with its background as smaller text, increasing font size is not a panacea.

"Normal" print is usually considered 11.5pt to 12pt, equivalent to 16px on screen. While smaller font may be legible — a user can make out letters at ~70% accuracy — that is not readable. A 16px font size is generally readable for people with normal vision. Someone with 20/40 needs twice that, about a 31px font. This is why the WCAG guidelines require that users have the ability to zoom any text larger.

While a text displayed too small is hard to read, so is a text that is too large. For users with 20/20 vision, with a text size greater than approximately 96px, reading speed decreases. Also, when there is a large disparity between the smallest and largest font size on a page, the larger text will become less readable if users enlarge the smaller text on the page, as most browsers zoom all text as the user zooms.

In general, for accessibility purposes, the more contrast, the better. That changes with animation. "Safer" animation means images with less contrast, not more. For more on color contrast in animation, see Three Flashes or Below Threshold Understanding SC 2.3.1

Also, note that icons need sufficient contrast for perception. See WCAG 2.1 technique G207

### Luminance

It is the difference in the luminance of a color that enables us to see the contrast. Relative luminance is defined in WCAG as "the relative brightness of any point in a colorspace, normalized to 0 for darkest black and 1 for lightest white."

This statement is of course accurate, but may be confusing when used in reference to the RGB color space, which is an integer between 0 and 255. White has 100% relative luminance, black has 0% relative luminance (in most but not all literature). Interpreting for the W3C standard above, that would mean that white, normalized to 1, would have an RGB value of `rgb(255 255 255)` and black, normalized to 0, would have an RGB value of `rgb(0 0 0)`. Note that black and white can also be written as `rgb(100% 100% 100%)` and `rgb(0% 0% 0%)` respectively, which may be more intuitive.

So, where do these numbers of 0 to 255 come from? Historically, graphics engines stored the color channels as a single byte, which means a range of integers between 0 and 255.

The luminances of the primary colors are different. Yellow has a greater luminance than blue, for example. This was done by way of design, *to achieve white alignment of the monitor*, according to the NASA document, "Luminance Contrast in Color Graphics"

A color contrast ratio is meaningless without its luminance component, and once luminance is established, the color contrast ratio can be established.

Where human perception is concerned, a difference in luminance matters more than a color difference. This is important, as luminance contrast enables the development of content that even those with color blindness can see. With this understanding, luminance may be manipulated so that colors that are difficult to see because of their low luminance could be made more legible by placing these colors against another with contrasting luminance. An interesting study by NASA on the color blue, for example, noted that this color, which has low luminance, can be made legible if *care was taken to achieve adequate luminance contrast* (From the article, Designing with blue)

Calculations for relative luminance are not casual ones. Luckily, there are online luminance and contrast checkers available, and even instructions on how to calculate relative luminance.

Perceiving color
----------------

Color is our perception of the narrow band of visible light, from red through yellow and green to blue. Our sensitivity to these various hues of color are not equal. The light sensitive cells in our eyes, called cones, are tuned to perceive some colors more than others. About 65% of cones are *most* sensitive to a yellow/green, but also respond to red (we'll call these "red" cones). 30% are green sensitive, and only 5% are blue sensitive. While there are far fewer blue-sensitive cones than the other two types, these cones are very sensitive, which partially makes up for their smaller numbers.

Deep, pure blue is perceived differently than other colors as blue cones do not contribute to luminance and we have far fewer blue cones than red or green.

![On the left is a cone mosaic of standard vision, and on the right is that of someone with protanopia where they are missing the red cones.](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance/conemosaics.jpg)

On the left is the central cone mosaic of standard vision, and on the right is that of someone with protanopia, a form of color vision deficiency, where they are missing the red cones. (Illustration by Mark Fairchild of RIT, Wikimedia Commons)

The red and the green cones join together to create luminance, which we can think of as lightness/darkness without regard to hue. Separately, the red, green, and blue cones allow for standard vision to perceive millions of colors. For accessibility, it's important to know that our brain processes luminance separately from color (hue and colorfulness).

Luminance provides for fine vision details, including differentiating edges and text. Hue and colorfulness carry a third of the detail of luminance. Image data compression takes advantage of this fact. As an example, h.264 video codec samples color at a fourth of the resolution of the luminance.

For accessibility, this means that luminance contrast is critically important for text. Color, as in hue and colorfulness, is important for *distinguishing* items such as different lines on a map or bars in a graph.

Another essential point to consider is the color or luminance that is surrounding a color. Colors appear differently depending on what is surrounding them. In the following image, both the yellow dots and the grey squares are the same sRGB color. Context-sensitive color perception makes them appear different; your brain's image processing adjusts the perception based on what it thinks is in shadow or not.

![An image of a checkerboard, where identical colors look different if they are in shadow](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance/yellowdotcheckershadow_dlyon.png)

The yellow dots in this image are identical colors on your monitor, but they appear different due to context. (Image D.Lyon)

Our contrast, lightness, and color perception are affected by the context of the nearby colors and other features of a design or image. This makes predicting contrast challenging. It is not as simple as a mathematical ratio between two colors.

To summarize, color is as much about human physiology and perception in the brain as it is about measuring light from a computer screen. It's also important to understand that the ambient light environment affects the ability to perceive color and contrast. Light and its measurements are linear, but human vision and perception are not.

Adaptation
----------

Our eyes don't adapt equally, in the same way, going from light areas to dark ones and vice versa. This is due to the physiological ways our eyes are built. This affects the ability of a user to read text against a background. At least two kinds of adaptation take place: local adaptation and adaptation to an ambient environment.

Local adaptation occurs right on the "page" a reader is looking at. For example, if you have blue text within a gray "highlighted" area, your eyes will perceive that exact blue text with a gray highlight differently if it is in a black `<div>`, or a white one. This is called *local* adaptation. This difference in the ability to perceive the text is affected even though the room's ambient lighting does not change.

The implication is that web developers who seek to improve the legibility of text against a background can take advantage of the principles of local adaptation.

Dark adaptation to low luminance is slow. When you come in from outside, where the sun is bright, and walk into a dark room, you are experiencing dark adaptation. It can take a few minutes to adjust to this.

Light adaptation is the reverse. Going from a dark room into bright sunlight is quicker but can also hurt.

The implication is that web developers who seek to improve the legibility of text in which the ambient conditions of a room have changed can take advantage of the `AmbientLightSensor` interface and the `prefers-contrast` media query.

Saturation
----------

 Saturation deserves a special mention in discussions about color ("hues") and accessibility. Generally speaking, most focus is on luminance when attempting to ensure enough contrast between text and its background or evaluating the possibility of inducing seizures in those sensitive to photosensitive seizures. One aspect of color ("hues"), independent of luminance, deserves special attention as it applies to accessibility: the concept of saturation. This is due to its ability to cause seizures in those susceptible to photosensitive seizures, regardless of color's luminance. As discussed in the particular case of red,
 the Epilepsy Foundation noted that, *irrespective of luminance, a transition to or from a saturated red is also considered a risk*.

Saturation is sometimes described as the "purity" or "intensity" of a color. Although these are good definitions for "pigments" in an artist's paint set, they are not as accurate as color definitions from a computer screen.

When it comes to color on a monitor, saturated colors are of a particular wavelength. While the definition of saturation for each color space may differ, saturation is readily measured. The key is to know which color space you are working in and be ready to convert it if necessary.

The color spaces most frequently considered when discussing photosensitivity are the RGB, HSL, and HSV, also known as HSB, color spaces. The HSV color space, which stands for *hue*, *saturation*, and *value*, and the synonym HSB, which stands for *hue*, *saturation*, and *brightness*), are represented in CSS as `hwb()` for *hue*, *whiteness*, and *blackness*.

It's important to know what color space you're working with. For example, saturated colors have a lightness of `0.5` in HSL, while in HWB, they have a value `1`. Saturation in the RGB color space is usually indicated by an RGB value of `255` or `100%` for the color in question. For example, a saturated red of hex value `#ff0000` has an RGB value of `rgb(255 0 0)` and an HSL value of `hsl(0 100% 50%)`. A different saturated red with a hex value of `#ff3300` has an RGB value of `rgb(255 51 0)` and an HSL value of `hsl(12 100% 50%)`. Both are "saturated" reds. They are two different "hues" but are both considered to be a saturated color.

Saturation is not brightness. Brightness refers to how much white or black is mixed in with a color. One can decrease saturation by adding white, black, or gray to the color; to take the example further, brightness can be increased by adding white, reducing saturation. A typical example is to add white to red to get the color pink. Pink is considered a desaturated red.

### Saturation and luminance

There is a loss of saturation at the extremes of luminance and the extremes of black and white. In NASA's effect of luminance on saturation, they point out that there is a loss of saturation at low luminances. and also, "…the loss of saturation at high luminances–the colors converge on white."

Color combinations
------------------

Contrast alone is not enough when it comes to accessibility considerations. In the case of animation, certain color combinations are more likely to cause photosensitive seizures to those who are susceptible to them than others. For example, alternating flashes between red and blue is more problematic than alternating flashes between green and blue. It has been theorized that this is because the "red" sensitive cones of our eyes, which tend to cluster around the fovea (near the center), are physically located at a different location than the "blue" sensitive cones of our eyes, which are located away from the fovea and towards the rims. The electrical signals from the eye to the brain have much to resolve between them as the information is processed in our brains.

Some colors more likely to cause epileptic seizures. Complexities underlying brain dynamics can be modulated by some color combinations more than the others. For example, red-blue flickering stimulus causes larger cortical excitation than red-green or blue-green stimulus.

Certain color combinations can be very problematic on a computer monitor or mobile device, and some color combinations can interfere with some impairments. The combination of red/blue is one such example.

* Never rely on hue alone for differentiating details. Adequate luminance contrast is required.
* The green in a monitor makes up the vast majority of luminance (light), so it will usually be a significant part of the lighter colors.
### Working with blue

Some people cannot differentiate between all colors. Some colors, such as pure blue, are low in luminance. Colors that are low in luminance should be the darker of contrasting colors. Blue is also very low in resolution. There are far fewer blue cones, and they are scattered in our peripheral vision and not present in our central vision. The human eye sees blue at a lower resolution than green and red.

This leads to some blue color use guidelines:

* Pure blues should typically be the darkest of two colors.
* When using blue as the lighter of the two colors, add green to increase contrast and improve readability.

The nature of blue light causes it to focus at a different location on the retina than red, so a pure red and a pure blue color that are immediately adjacent and touching may "shimmer" when next to each other.

The special case of red
-----------------------

Not all colors ("hue") are processed similarly by our brains. Human physiology and psychology are affected by the color red, generally speaking, in ways different from that of other colors. We respond physiologically as well as psychologically to colors. For example, it has been demonstrated that some colors are more likely to cause epileptic fits than others. Some devices offer a "grayscale" setting as an accessibility option" which can help people who are photo-sensitive. To mimic the grayscale setting, use the CSS `filter` property with a `grayscale()` or `saturate()` `<filter-function>`.

### Saturated red

"Saturated Red" is a special, dangerous case, and there are special tests for it.

The concept of color saturation is a difficult one to understand when only looking at numbers and terminology, so consider looking at the image below to illustrate the concept of saturation in a color:

![Red Saturation from Wikimedia Commons svg saved as png Attribution: Datumizer [CC0]](/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance/320px-red_saturations.svg.png)

The same "color" proceeds from least saturated on the left-hand side to most saturated on the right-hand side.

*More than one "red" color may be considered a "saturated" red.* For example, the color `#990000` at `hsl(0 100% 30%)` is fully saturated but is less bright than the colors described above. Similarly, the color `#8b0000` also has a saturation of 100%.

Not all saturated reds may be represented well in the RGB spectrum or other spectrums commonly used in web development. According to Wikipedia's page on "Shades of Red", the color "Carmine" is a saturated red which, in its pigment form, mostly contains red light with wavelengths longer than 600nm; the article makes the special note that "Carmine" is close to the extreme spectrum. This places it far beyond standard gamuts (RGB and CMYK), and its given RGB value is a poor approximation only."

### Saturated red flashing

In addition to a red environment affecting the cognitive function of those with traumatic brain injury, color in the red spectrum wavelength requires special attention and tests.

Gregg Vanderheiden, when testing the *Photosensitive epilepsy analysis tool*, noted seizure rates were much higher than expected. They found that we are much more sensitive to saturated red flashing. (See the video, The Photosensitive epilepsy analysis tool.)

### Flashing and seizures

Continuous flashing brighter/darker at rates higher than three flashes per second has been shown to induce photic seizures in some people. It has also been found that specific, very regular, high-contrast patterns, such as parallel white and black stripes, can also induce seizures.

The Epilepsy Foundation of America researched photic- and pattern-induced seizures. The study resulted in several fundamental guidelines:

1. Single, double, or triple flashes in one second are acceptable, but a sequence of flashes is not recommended when more than three flashes happen within one second.
2. When displaying light and dark stripes, the pattern should display no more than five light–dark pairs of stripes, if the stripes change direction, oscillate, flash, or reverse in contrast or eight light–dark pairs of stripes, if the pattern is unchanging or continuously and smoothly drifting in one direction.

The consensus recommendations are in this brief paper, Photic- and Pattern-induced Seizures: Expert Consensus of the Epilepsy Foundation of America. Some additional insights are available in this UK paper covering guidelines for preventing seizures..

Psychophysical aspects of color
-------------------------------

Color as in hues and saturation can affect our mood, and enhance — or de-enhance — our interactive experiences.

### Examples of color's effect beyond vision

* **Color can be culturally dependent:** A Cross-Cultural Study of the Affective Meanings of Color
* **Color affects our emotions:** Color and emotion: effects of hue, saturation, and brightness
* **Higher contrasts can also have a positive affect on our emotions:** Emotion Variation from Controlling Contrast of Visual Contents through EEG-Based Deep Emotion Recognition
* **Some colors can affect our perception of time:** Color and time perception: Evidence for temporal overestimation of blue stimuli
* **Blue also has a significant effect on brightness and glare:** Blue and glare & brightness
* **Red tinted glasses can provide increased happiness or joy:** Looking Through "Rose-Tinted" Glasses: The Influence of Tint on Visual Affective Processing
* **Red is well known to have significant effects on our behavior:** How the Color Red Influences Our Behavior, Scientific American, S. Martinez-Conde, Stephen L. Macknik
* **Red Environment:** Studies have shown that for those who suffer Traumatic Brain Injury, cognitive function is reduced in a red environment.
See also
--------

* Accessibility
* Accessibility learning path
* CSS `color` property
* `<color>` data type
* Web accessibility for seizures and physical reactions
* How the Color Red Influences Our Behavior Scientific American By Susana Martinez-Conde, Stephen L. Macknik on November 1, 2014
* Red Desaturation The human eye is so sensitively "tuned" to red, that ophthalmologists set up a test using it, assessing the integrity of the optic nerve.
* Photic- and pattern-induced seizures: expert consensus of the Epilepsy Foundation of America Working Group