我可以将 CSS 样式应用于元素名称吗?

2022-01-10 00:00:00 css-selectors html css

我目前正在从事一个项目,我无法控制我应用 CSS 样式的 HTML.而且 HTML 没有很好地标记,因为没有足够的 id 和 class 声明来区分元素.

I'm currently working on a project where I have no control over the HTML that I am applying CSS styles to. And the HTML is not very well labelled, in the sense that there are not enough id and class declarations to differentiate between elements.

所以,我正在寻找可以将样式应用于没有 id 或 class 属性的对象的方法.

So, I'm looking for ways I can apply styles to objects that don't have an id or class attribute.

有时,表单项具有名称"或值"属性:

Sometimes, form items have a "name" or "value" attribute:

<input type="submit" value="Go" name="goButton">

有没有一种方法可以应用基于 name="goButton" 的样式?价值"呢?

Is there a way I can apply a style based on name="goButton"? What about "value"?

这种情况很难找到,因为 Google 搜索会发现各种情况,其中名称"和价值"等广义术语会出现在网页中.

It's the kind of thing that's hard to find out because a Google search will find all sorts of instances in which broad terms like "name" and "value" will appear in web pages.

我有点怀疑答案是否定的......但也许有人有一个聪明的黑客?

I'm kind of suspecting the answer is no... but perhaps someone has a clever hack?

任何建议将不胜感激.

推荐答案

可以使用属性选择器,

input[name="goButton"] {
  background: red;
}

<input name="goButton">

请注意,IE6 不支持它.

Be aware that it isn't supported in IE6.

更新:在 2016 年,您几乎可以随意使用它们,因为 IE6 已死.http://quirksmode.org/css/selectors/

Update: In 2016 you can pretty much use them as you want, since IE6 is dead. http://quirksmode.org/css/selectors/

http://reference.sitepoint.com/css/attributeselector

相关文章