具有特殊字符的CSS类 [英] CSS classes with special characters

查看:44
本文介绍了具有特殊字符的CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WebApp,需要在其中使用CSS文件操作某些元素.CSS类包含方括号和其他特殊字符.至少Chrome似乎并没有直接接受它们.

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 accept them directly.

<div class="profileElement profile[~redString]">123</div>

该课程甚至有效吗?有没有一种使用类名的方法?我想要:

Is this class even valid? Is there a way to use the classname? I want:

.profile[~redString]{
    color: red; }

当我用反斜杠铬转义〜时,可以将其注入(F12-> Elements->右上角的加号)到页面,但显示为灰色的css,这意味着该类不存在于页面.

When I escape the ~ with a backslash chrome allows me to inject (F12 -> Elements -> the plus symbol on the top right) it to the page but displays the css in grey, meaning the class does not exist in the page.

该课程有效吗?如果是这样,我将如何使用它?

Is that class valid? If so, how would I use it?

推荐答案

该课程甚至有效吗?

Is this class even valid?

这取决于您要验证的内容.

It depends on what you're validating against.

profile [〜redString] 是有效的HTML类名,通过将标记放在验证器中来举例说明.

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

但是, .profile [〜redString] 不是有效的CSS选择器,因为是一个特殊的符号,如您所知,并且不在CSS解析器期望的位置.当您逃脱时,您会得到

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]

这是一个有效的选择器,但含义完全不同.它表示一个类名为 profile 的元素,以及一个名为〜redString 的属性.它不会代表一个类名称,其元素名称恰好是 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]"]

在此CSS2.1属性选择器,其作用类似于类选择器.

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>
  <div class="profileElement profile[~redString]">123</div>
  <div class="profileElement profile[~redString]">456</div>
</div>

这篇关于具有特殊字符的CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆