仅为 DOM 的一部分创建样式重置的最佳方法是什么?

What's the best way to create a style reset for only a portion of the DOM?

提问人:JoshNaro 提问时间:12/3/2008 最后编辑:Carl CameraJoshNaro 更新时间:12/4/2008 访问量:345

问:

我正在尝试创建一个仅针对我的控件的 css 重置。因此,HTML 将如下所示:

<body>
  <img class="outterImg" src="sadkitty.gif" />
  <div id="container" class="container">
    <img class="innerImg" src="sadkitty.gif" />
    <div class="subContainer">
      <img class="innerImg" src="sadkitty.gif" />
    </div>
  </div>
  <img class="outterImg" src="sadkitty.gif" />
</body>

CSS是我遇到的问题,但我目前正在处理这个问题:

img 
{
  // Bad style declarations for the entire page
  border: solid 3px red;  
  width: 50px;
}

.container img, .container div, .container etc.
{
  // Style reset for specific elements within my control "container"
  border: solid 3px blue;
  width: 100px;
}

.innerImg img
{
  // The target style for the specific class/element within the control
  border: solid 3px green;
  width: 200px;
}

问题是“.innerImg img”并没有像我预期的那样覆盖“.container img”。那么,重置“容器”元素中所有元素的样式,然后在该元素中的类上放置样式的最佳方法是什么?

css -重置 css -特异性

评论


答:

0赞 Joel Meador 12/3/2008 #1

我怀疑这会导致接近您想要的。

img  
{  
  border: solid 3px red;  
  width: 50px;  
}  
.container .innerImg, .container div  
{  
  border: solid 3px blue;  
  width: 100px;  
}  
.container .subContainer  
{  
  border: none;  
}  
.subContainer .innerImg  
{  
  border: solid 3px green;  
  width: 200px;  
}
3赞 Jesse Millikan 12/3/2008 #2

选择器引用具有类 innerImg 的元素内的 img 元素。您的文档中没有类似内容。.innerImg img

你可能想要的是.img.innerImg

除此之外,还有一个简短的选择器特异性计算,用于确定遵循哪条规则。(该链接包含我在任何文档中最喜欢的新限定词:“在具有大基数的数字系统中”)