What is lang Attribute in HTML and How to Use It
lang attribute in HTML specifies the language of the content inside an element, usually the whole page. It helps browsers and assistive technologies understand and present the text correctly, improving accessibility and search engine results.How It Works
The lang attribute tells the browser what language the text on the page is written in. Think of it like a label on a book that says "This book is in English" or "This book is in Spanish." This helps the browser choose the right pronunciation for screen readers and display the correct characters.
When you set the lang attribute on the <html> tag, it applies to the whole page. You can also set it on smaller parts if your page has multiple languages, like a quote in French inside an English article. This way, each part is read or processed correctly.
Example
This example shows how to set the language of a webpage to English using the lang attribute on the <html> tag.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lang Attribute Example</title> </head> <body> <p>Hello! This page is in English.</p> </body> </html>
When to Use
Use the lang attribute on the <html> tag for every webpage to declare its main language. This helps search engines show your page to the right audience and improves accessibility for people using screen readers.
If your page contains sections in different languages, add the lang attribute to those specific elements. For example, a blog post in English with a French quote should mark the quote with lang="fr".
Setting the language correctly is important for:
- Screen readers to pronounce words properly
- Search engines to index your page accurately
- Browsers to apply correct hyphenation and spell checking
Key Points
- The
langattribute defines the language of the content. - It is usually set on the
<html>tag for the whole page. - Use it on smaller elements for mixed-language content.
- Helps accessibility tools and search engines.
- Improves user experience by enabling correct pronunciation and text handling.
Key Takeaways
lang attribute on the <html> tag to declare your page's language.lang on smaller elements when your page has multiple languages.lang attribute improves accessibility and search engine understanding.lang to apply correct text rules like hyphenation and spell check.