在兄弟元素上应用没有class和id的CSS

时间:2018-05-04 03:51:15

标签: html css

我需要在CSS文件的以下div上应用不同的背景颜色,而不使用类或ID

<div>This is Blue</div>
<div>This is Yello</div>
<div>This is Red</div>

如果不使用JavaScript或jQuery

,有没有办法做到这一点

4 个答案:

答案 0 :(得分:5)

由于div的当前结构是 Not Nested ,因此使用 CSS :nth-child() 是不合适的。 对于这种情况,我们可以使用CSS中的Sibling Selector

  1. 相邻的兄弟选择器(+)
    相邻的兄弟选择器选择与指定元素相邻的兄弟元素的所有元素。
    以下示例选择紧跟<p>元素之后放置的所有<div>元素:

      

    div + p {       背景颜色:黄色;   }

  2. 一般兄弟选择器(〜)
    通用兄弟选择器选择所有元素作为指定元素的兄弟元素 以下示例选择<p>个元素的所有<div>个元素:

      

    div~p {       背景颜色:黄色;   }

  3. 希望它有所帮助。

答案 1 :(得分:2)

当然,你可以像这样使用CSS :nth-child()选择器:

div:nth-child(1) {
  background-color: blue;
}

div:nth-child(2) {
  background-color: yellow;
}

div:nth-child(3) {
  background-color: red;
}

答案 2 :(得分:1)

div:nth-child(1){
background:blue;
}
div:nth-child(2){
background:yellow;
}
div:nth-child(3){
background:red;
}
<div>This is Blue</div>
<div>This is Yello</div>
<div>This is Red</div>

答案 3 :(得分:0)

一个奇怪的方法是使用nth-of-type,它可以工作,但如果与页面上的许多其他div一起使用,可能会变得格外复杂。

我添加了一些额外的div只是为了演示这个方法足够有选择性。

&#13;
&#13;
.thisone div:nth-of-type(1n) {
  background: rgb(100, 100, 100);
}

.thisone div:nth-of-type(2n) {
  background: rgb(80, 80, 80);
}

.thisone div:nth-of-type(3n) {
  background: rgb(60, 60, 60);
}

.thisone div:nth-of-type(4n) {
  background: rgb(40, 40, 40);
}

.thisone div:nth-of-type(5n) {
  background: rgb(20, 20, 20);
}
&#13;
<div>
  <div>First</div>
  <div>Second</div>
  <div>Third</div>
  <div>Fourth</div>
  <div>Fifth</div>
</div>
<br>
<div class="thisone">
  <div>First</div>
  <div>Second</div>
  <div>Third</div>
  <div>Fourth</div>
  <div>Fifth</div>
</div>
<br>
<div>
  <div>First</div>
  <div>Second</div>
  <div>Third</div>
  <div>Fourth</div>
  <div>Fifth</div>
</div>
&#13;
&#13;
&#13;

相关问题