Explain Codes LogoExplain Codes Logo

Best way to encode Degree Celsius symbol into a web page?

html
best-practices
responsive-design
web-development
Nikita BarsukovbyNikita Barsukov·Oct 29, 2024
TLDR

For displaying the Degree Celsius symbol (°C), use the HTML entity °C.

<p>Current temperature: 20&deg;C</p> <!-- Brrr… I need a sweater! -->

Displays as: Current temperature: 20°C.

Ensuring UTF-8 charset declaration

Before displaying special characters, set your web page's charset to UTF-8. This meta tag belongs in the <head> section to ensure correct rendering across platforms:

<meta charset="utf-8"> <!-- Because "unicorns" need their encoding too! -->

Addressing automatic line breaks

A common issue is line breaks or wrapping disrupting text flow. To prevent this, wrap the temperature and symbol in a <nobr> tag:

<nobr>20&deg;C</nobr> <!-- Keep the "warmth" and its symbol together! -->

Or you can adopt a CSS solution:

.temperature { white-space: nowrap; /* Because "temperatures" don't like to be "broken up"! */ }

Incorporating custom fonts

When the Degree Celsius symbol needs a specific style or font, use the @font-face rule with a custom font:

@font-face { font-family: 'CustomFont'; /* Make it "fancy" */ src: url('CustomFont.woff2') format('woff2'); } .temperature { font-family: 'CustomFont', sans-serif; }

Character References: Unicode and CSS Content

You can opt for the Unicode character reference &#x2103; as an alternative to HTML entities:

<p>Current temperature: 20&#x2103;</p> <!-- For folks who find "&deg;" too mainstream -->

For a CSS-specific application, use the content property along with the ::after pseudo-element:

.temp::after { content: '\00B0C'; /* It's getting hot in here! */ }

Improving accessibility

Making your content accessible to all readers, including using assistive technologies, is crucial. Use the aria-label to increment semantics:

<span aria-label="degrees Celsius">20&deg;C</span> <!-- Let the "robots" understand too! -->

Using <sup> for styling the degree symbol makes it visually distinct:

<p>Current temperature: 20<sup>&deg;</sup>C</p> <!-- "C" for "Cool" -->

Verify Your Encoding

Don't forget to test your encoding across various devices and browsers to ensure consistency. Even the smallest discrepancy can affect user experience.

Here are some best practices:

  • Declare the document type and character encoding.
  • Encode special characters properly.
  • Use CSS to fix display issues.
  • Keep yourself updated on the latest web standards and practices.

Ensuring Server-Sided Consistency

Encoding often falls short when server settings aren't synchronized with the webpage's, leading to inconsistent outputs. Double-check by verifying the HTTP headers:

Content-Type: text/html; charset=utf-8 /* Because communication is key! */