142

在以下 HTML

<div id="content" role="main">

id 可以通过#contentCSS 访问。我如何访问role="main".

4

7 回答 7

234

使用 CSS 属性选择器:

https://developer.mozilla.org/en-US/docs/CSS/Attribute_selectors

例如:

div[role=main]
于 2012-10-15T09:27:28.683 回答
19

像这样访问它应该可以工作:#content[role="main"]

于 2012-10-15T09:27:46.763 回答
18

编写访问该特定 div 的选择器的最短方法是简单地使用

[role=main] {
  /* CSS goes here */
}

前面的答案没有错,但它们依赖于您使用 div 或使用特定 id。使用此选择器,您将能够拥有各种疯狂的标记,并且它仍然可以工作,并且您可以避免特异性问题。

[role=main] {
  background: rgba(48, 96, 144, 0.2);
}
div,
span {
  padding: 5px;
  margin: 5px;
  display: inline-block;
}
<div id="content" role="main">
  <span role="main">Hello</span>
</div>

于 2016-05-26T08:52:51.007 回答
16

当然你可以在这种模式下做:

 #content[role="main"]{
       //style
    }

http://www.w3.org/TR/selectors/#attribute-selectors

于 2012-10-15T09:28:27.870 回答
6

我们可以用

 element[role="ourRole"] {
    requried style !important; /*for overriding the old css styles */
    }
于 2018-04-26T14:48:09.380 回答
4

关注此线程以获取更多信息

CSS 属性选择器:如果自定义属性具有值,则应用类?另外,它可以在IE7+中工作吗?

并学习 css 属性选择器

http://www.w3schools.com/css/css_attribute_selectors.asp

于 2012-10-15T09:29:12.990 回答
2

请用 :

 #content[role=main]{
   your style here
}
于 2012-10-15T09:33:44.393 回答