Skip to content Skip to sidebar Skip to footer

Css Classes With Special Characters

I have a WebApp where I need to manipulate certain elements using a CSS file. The CSS classes contain square brackets and other special characters. At least chrome doesn't seem to

Solution 1:

Is this class even valid?

It depends on what you're validating against.

profile[~redString] is a valid HTML class name, exemplified by putting the markup through a validator.

However, .profile[~redString] is not a valid CSS selector, because the ~ is a special symbol as you have found out, and it's not in a place where the CSS parser would expect it. When you escape it, you get

.profile[\~redString]

which is a valid selector, but with a completely different meaning. It represents an element with a class name profile, as well as an attribute called ~redString. It does not represent an element with a class name that is exactly profile[~redString].

To match this element, you need to escape the square brackets as well. This will result in the entire stream of characters being treated as a single identifier:

.profile\[\~redString\]

Alternatively, you can use an attribute selector instead to make things cleaner:

[class~="profile[~redString]"]

Notice the ~= in this CSS2.1 attribute selector, which works similarly to a class selector.

See both selectors in action:

:first-child.profile\[\~redString\],
:last-child[class~="profile[~redString]"] {
  color: red;
}
<div><divclass="profileElement profile[~redString]">123</div><divclass="profileElement profile[~redString]">456</div></div>

Post a Comment for "Css Classes With Special Characters"