html - 我将如何使用 CSS 选择它?

标签 html css css-selectors

假设我有以下内容..

<div>
    <div>
        <div>
            <div></div>  <<<Select this one..
            <div></div>  <<<Not this one..
            <div></div>  <<<Select this one..
            <div></div>  <<<Select this one..
        </div>
    </div>
</div>

如何在不添加任何类或 ID 的情况下选择这 3 个 div?这可能吗?

最佳答案

您可以使用 :not():nth-child()伪类。

div > div > div > div:not(:nth-child(2)){
  color: red;
}
<div>
  <div>
    <div>
      <div>Test</div> 
      <div>Test</div>
      <div>Test</div>
      <div>Test</div>
    </div>
  </div>
</div>

Demo in jsFiddle

Note: For ie8 support, you could use the same selector in jQuery and style your element that way.

$("div > div > div > div:not(:nth-child(2))")
	.css("background-color", "yellow")
<div>
  <div>
    <div>
      <div>Test</div> 
      <div>Test</div>
      <div>Test</div>
      <div>Test</div>
    </div>
  </div>
</div>

<!-- External Resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于html - 我将如何使用 CSS 选择它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793826/

相关文章:

java - 更改从 servlet 类返回的 div 类位置

html - 我正在尝试将 SVG 文件放入 div 中,但调整 SVG 的大小无法正常工作

html - 将页面添加到 slider (html)

javascript - 动态创建元素的绝对定位

Javascript 随机图像旋转器调整图像大小?

javascript - document.getElementById JS HTML CSS

css - Node WebKit 更改源代码中的打印设置

html - 如何使带有背景附件的图像居中

html - 如何选择最后一个选择器?

html - 无法让 ":last-child"选择器在我的布局上工作。我错过了什么?