Sub topic 3
Spaces, underscores and escaping
This chapter assumes you know basic HTML and CSS, including how multi-value properties like grid-template-columns are written. It also assumes you have used Tailwind utilities such as p-4 and hover:bg-blue-500, and that you have seen the square-bracket form of an arbitrary value. Here you learn how Tailwind turns underscores into spaces, where it keeps them, and how to write a literal underscore when you need one.
Why spaces are a problem
A utility class is one token in a class attribute, and the browser splits that attribute on whitespace. A class name therefore cannot contain a space. Many CSS values are lists separated by spaces:
grid-template-columns: 1fr 500px 2frbox-shadow: 0 35px 60px -15px rgba(0, 0, 0, 0.3)font-family: Open Sansmargin: 0 auto
If you wrote grid-cols-[1fr 500px 2fr] in HTML, the browser would see three separate classes: grid-cols-[1fr, 500px and 2fr]. None of them would match anything.
Tailwind's answer is to let you write an underscore where you want a space. When it generates CSS for a class, it converts the underscores inside the square brackets into spaces.
<div class="grid grid-cols-[1fr_500px_2fr] gap-[10px]">
<div>Sidebar</div>
<div>Content</div>
<div>Aside</div>
</div>For the grid-cols-[1fr_500px_2fr] class, Tailwind emits CSS like this:
.grid-cols-\[1fr_500px_2fr\] {
grid-template-columns: 1fr 500px 2fr;
}The selector keeps the underscores because it must match the class name in your HTML exactly. Only the declaration value is converted. This is the key mental model: the class name is the source text, and the CSS value is the source text after a transformation.
Common places you need underscores
Any value that is a space-separated list needs underscores. The following examples cover the most frequent cases.
<div class="shadow-[0_35px_60px_-15px_rgba(0,0,0,0.3)]"></div>
<h1 class="font-['Open_Sans']">Title</h1>
<div class="bg-[linear-gradient(to_right,#ff7e5f,#feb47e)]"></div>
<div class="m-[0_auto]"></div>
<div class="transition-[opacity_200ms_ease-out]"></div>Each one maps to a CSS value with ordinary spaces:
| Class | Generated declaration |
|---|---|
| `shadow-[0_35px_60px_-15px_rgba(0,0,0,0.3)]` | `box-shadow: 0 35px 60px -15px rgba(0,0,0,0.3)` |
| `font-['Open_Sans']` | `font-family: 'Open Sans'` |
| `bg-[linear-gradient(to_right,#ff7e5f,#feb47e)]` | `background-image: linear-gradient(to right,#ff7e5f,#feb47e)` |
| `m-[0_auto]` | `margin: 0 auto` |
Notice that commas need no special treatment. A comma is a legal character in a class name, so rgba(0,0,0,0.3) can be written without spaces after the commas. You only need an underscore where CSS requires whitespace to separate tokens.
Quotes work the same way. The quotes in font-['Open_Sans'] are part of the class name and are passed through to the CSS. Quoting is optional for font names without special characters, but it is good practice for multi-word family names.
Spaces inside calc()
CSS requires whitespace around + and - inside calc(). calc(50%-2rem) is invalid CSS, because the parser reads -2rem as a negative length rather than a subtraction. Tailwind compensates: it inserts spaces around the math operators +, -, * and / inside calc() for you. That is why the spine example works as written:
<div class="absolute top-[117px] left-[calc(50%-2rem)] w-[317px] bg-[#bada55]"></div>Here left-[calc(50%-2rem)] becomes left: calc(50% - 2rem). You may also write the underscores yourself, as in left-[calc(50%_-_2rem)], and the result is the same. Many teams prefer the underscore form because it reads like the CSS it produces and does not depend on the automatic normalization. Pick one style and keep it consistent in a project.
The automatic spacing applies to math functions. Outside of them, a hyphen is just a hyphen. In m-[-4px] the minus sign is part of the number, which is why it survives untouched.
Where Tailwind keeps the underscore
Converting every underscore would break values where an underscore is a normal character and spaces are not allowed. The main example is a URL. A file named what_a_rush.png must keep its underscores, or the browser requests a different file.
Tailwind therefore leaves underscores alone in contexts where a space would never be valid. The most important is url():
<div class="bg-[url('/img/what_a_rush.png')]"></div>This generates background-image: url('/img/what_a_rush.png'), with the underscores intact.
Tailwind's own documentation states this rule: it preserves the underscore in situations where underscores are common but spaces are invalid, with URLs as the example. Do not assume the rule covers every function. If you are unsure, build the CSS, look at the generated declaration, and check it.
Your project's Tailwind version matters for edge cases. Details such as which functions are protected, and how custom property names are handled, have changed between major versions. Check the output for the version you actually use.
Writing a literal underscore
Some values contain a real underscore in a place where a space would also be valid. A quoted string in content is the standard case. By default, underscores become spaces, which is what you usually want:
<div class="before:content-['Hello_World']"></div>This produces content: 'Hello World'.
If you want the text hello_world with a real underscore, escape it with a backslash:
<div class="flex items-center before:content-['hello\_world']"></div>This produces content: 'hello_world'. The backslash tells Tailwind to skip the conversion for that one underscore, and the backslash itself is removed from the output.
You can mix both in one value. In before:content-['a\_b_c'], the first underscore is escaped and stays, and the second is converted. The result is the string a_b c.
Escaping inside JavaScript strings
A backslash needs extra care when the class is written inside a JavaScript or JSX string. In an ordinary JS string literal, \_ is an escape sequence that produces a plain _. The runtime class would lose the backslash, and it would no longer match the CSS selector Tailwind generated.
In JSX, a string written as an attribute value (className="...") does not process escape sequences, so the backslash survives. In a normal JavaScript string, double the backslash, or use String.raw:
// The backslash is consumed by the string literal, so the DOM class has no backslash.
const wrong = "before:content-['hello\_world']";
// Doubled backslash: the runtime string contains one backslash.
const doubled = "before:content-['hello\\_world']";
// String.raw keeps the backslash exactly as written.
const raw = String.raw`before:content-['hello\_world']`;
console.log(wrong); // before:content-['hello_world']
console.log(doubled); // before:content-['hello\_world']
console.log(raw); // before:content-['hello\_world']Run this with Node and compare the three lines. Only the last two keep the backslash that the generated CSS selector expects. If an escaped underscore seems to do nothing, print the final string and check for the backslash first.
Underscores in arbitrary variants
The same rule applies to arbitrary variants, which later chapters cover in detail. Inside the brackets, an underscore becomes a space, and in a selector a space is the descendant combinator:
<div class="[&_p]:mt-4">
<p>Gets a top margin.</p>
<section><p>Also gets a top margin.</p></section>
</div>The variant [&_p] becomes the selector & p, so every <p> inside the element is matched at any depth. Compare it with [&>p], which becomes & > p and matches only direct children. The child combinator > needs no underscore because a selector does not need whitespace around it.
This is a good reason to learn the conversion rule now. A missing underscore in a selector usually yields a different selector, not an error. For example, [&p] would mean "this element, if it is also a p", not "a p inside this element".
Underscores in CSS variable names
Custom property names often use hyphens, as in --hero-size. If a name includes an underscore, such as --hero_size, you run into the same conversion. Whether Tailwind leaves the name alone depends on its version and on where the name appears.
The safe approach avoids the question:
- Name your custom properties with hyphens, not underscores.
- If you must reference a name that contains an underscore, test the generated CSS, or escape the underscore with a backslash.
<section class="[--scroll-offset:56px] lg:[--scroll-offset:44px] scroll-mt-[var(--scroll-offset)]">
...
</section>Every name here uses hyphens, so the example has no ambiguity. Hyphenated names are also the convention in CSS, so following it costs you nothing.
A debugging checklist
When an arbitrary value does nothing, check the following in order:
- Is there a literal space in the class? If so, the browser has split it into several classes. Replace the space with an underscore.
- Did the underscore turn into a space where you wanted an underscore? Escape it with a backslash, or check whether you are inside a protected context such as
url(). - Does the class appear in full in your source files? Dynamic construction defeats the scanner, and a later chapter covers it.
- Does the generated CSS contain the declaration you expect? Open the built stylesheet or the browser's developer tools and read the actual value.
- Is the value valid CSS once spaces are restored? A conversion cannot fix
calc(50%2rem)or a missing comma.
The summary table below shows how the main cases behave.
| You write | Tailwind produces | Why |
|---|---|---|
| `grid-cols-[1fr_2fr]` | `1fr 2fr` | Underscore becomes a space |
| `content-['a_b']` | `'a b'` | Underscore becomes a space inside quotes |
| `content-['a\_b']` | `'a_b'` | Backslash keeps the underscore |
| `bg-[url('/a_b.png')]` | `url('/a_b.png')` | Underscores in `url()` are preserved |
| `left-[calc(50%-2rem)]` | `calc(50% - 2rem)` | Spaces are added around operators in `calc()` |
| `[&_p]:mt-4` | selector `& p` | Underscore becomes a descendant combinator |
Common errors
- Typing a real space. Editors and formatters sometimes wrap long class lists. A wrapped class that contains a space is broken in two. Keep each arbitrary class on one line, with underscores for spaces.
- Using hyphens as separators.
shadow-[0-35px-60px]is not0 35px 60px. Hyphens are never converted. - Forgetting the escape in JS. As shown above,
"\_"loses its backslash in a normal string literal. - Over-escaping. Escaping an underscore in a context that already preserves it, such as
url(), is unnecessary and may leave a stray backslash in the output. Use the escape only when the underscore would otherwise be converted. - Assuming a space is always an error. Spaces inside quoted strings in a template literal or a
classNameexpression are fine as JavaScript. The problem is only a space inside a single class token.
Exercise
You write <div class="before:content-['snake_case_name']"></div> and the page shows "snake case name". How do you change the class so the page shows "snakecasename"?
Show answer
Escape each underscore with a backslash: before:content-['snake\_case\_name']. Tailwind converts unescaped underscores to spaces, and the backslash keeps the underscore. In a normal JavaScript string, write the backslash twice (\\_) or use String.raw so the backslash reaches the DOM.
Exercise
What CSS declaration does shadow-[0_8px_24px_-6px_rgba(0,0,0,0.25)] generate, and why are there no underscores around the commas inside rgba()?
Show answer
It generates box-shadow: 0 8px 24px -6px rgba(0,0,0,0.25). The underscores stand for the spaces that separate the five shadow values. Commas are legal in class names and CSS does not require whitespace after them, so they need no underscore.
Exercise
Explain the difference between [&_p]:mt-4 and [&>p]:mt-4 on a <div> that contains a <section> with a <p> inside it.
Show answer
[&_p] becomes the selector & p, a descendant combinator, so it matches the <p> inside the <section>. [&>p] becomes & > p, a child combinator, so it matches only paragraphs that are direct children of the <div> and does not match the nested one.