View video tutorial

HTML charset Attribute

HTML

The HTML charset attribute specifies the character encoding for an HTML document or an external resource.

Definition and Usage


➔ This attribute ensures that the text content of a webpage or linked file is displayed correctly across different browsers and operating systems.

➔ UTF-8 supports a wide variety of international characters and symbols, so UTF-8 is the universally recommended character set.

➔ It's a good idea to put meta charset="UTF-8" as the first element inside the <head> so that the browser can interpret the document correctly from the start.

➔ When used with the <script> element, the charset attribute specifies the character encoding used in an external script file, and when used with the <a> tag, the charset attribute specifies the character encoding used in an externally linked resource.

The charset attribute syntax

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title for the page</title>
</head>

Important points about the charset attribute:


➔ The charset attribute should be declared as early as possible within the first 1024 bytes of the document so that the browser can find the charset instruction before it incorrectly encodes any characters.

➔ The charset attribute tells the browser to use a specific character set when converting human-readable characters to binary bytes, and vice versa.

➔ It is important to specify the charset for a web page to ensure display consistency across different browsers and to prevent characters from displaying incorrectly.

➔ UTF-8 is the recommended web standard for character encoding because it includes all characters and symbols for almost all languages ​​in the world.

Code Sample
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Page Title here</title>
</head>
<body>
  <!-- Page Content goes here -->
</body>
</html>

Code Sample
<script charset="utf-8" src="pathofthe_script.js"></script>

Code Sample
<a href="https://w3context.com" charset="UTF-8">w3context.com</a>

Applies to

This attribute can be used on the following element.

Attribute Element
charset <meta>, <script>

Example
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Page Title here</title>
</head>
<body>
  <h2>HTML charset attribute example</h2>
  <p>The charset attribute specifies the character encoding for an HTML document.</p>
</body>
</html>

Click on the "copy" button and try this example in your project.