CSS first-child:部分不在bootstrap中工作

时间:2018-01-06 13:31:36

标签: css twitter-bootstrap

如果你看下面的代码,我有一行有2列。两列都具有应用于它们的完全相同的CSS代码。但是,.leftMenu:first-child:before在第一列上完全正常,但.pageContent:first-child:before根本不起作用。

.pageContent:first-child:before应用于第一列时,它再次完美地运行。这里发生了什么?我该如何解决?



.leftMenu {
  background-color: #0e0e0e;
  border-left: 1px solid #070707;
}

.leftMenu:first-child:before {
  content:'';
  position:absolute;
  height:20px;
  width: 100%;
  background: -webkit-linear-gradient(top, #151515, #0e0e0e);
  background: -moz-linear-gradient(top, #151515, #0e0e0e);
  background: -o-linear-gradient(top, #151515, #0e0e0e);
  background: linear-gradient(to bottom, #151515, #0e0e0e);
  top:0px;
  left:0;
}

.pageContent {
  background-color: #0a0a0a;
  border-left: 1px solid #070707;
}

.pageContent:first-child:before {
  content:'';
  position:absolute;
  height:20px;
  width: 100%;
  background: -webkit-linear-gradient(top, #151515, #0a0a0a);
  background: -moz-linear-gradient(top, #151515, #0a0a0a);
  background: -o-linear-gradient(top, #151515, #0a0a0a);
  background: linear-gradient(to bottom, #151515, #0a0a0a);
  top:0px;
  left:0;
  border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-sm-2 leftMenu">
  </div>
  <div class="col-sm-10 pageContent">
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

那是因为IValue不是它的父亲的第一个孩子,或者.pageContent在这种情况下,而是.row所以你可以使用

last-child

.pageContent:last-child:before

当你使用.pageContent:nth-child(2):before 时,如果该元素也是其父元素的第一个子元素而不是该类的第一个元素而不是该元素的第一个子元素,它将选择该类的元素。

classSelector:first-child
.leftMenu {
  background-color: #0e0e0e;
  border-left: 1px solid #070707;
}

.leftMenu:first-child:before {
  content: '';
  position: absolute;
  height: 20px;
  width: 100%;
  background: -webkit-linear-gradient(top, #151515, #0e0e0e);
  background: -moz-linear-gradient(top, #151515, #0e0e0e);
  background: -o-linear-gradient(top, #151515, #0e0e0e);
  background: linear-gradient(to bottom, #151515, #0e0e0e);
  top: 0px;
  left: 0;
}

.pageContent {
  background-color: #0a0a0a;
  border-left: 1px solid #070707;
}

.pageContent:last-child:before {
  content: '';
  position: absolute;
  height: 20px;
  width: 100%;
  background: -webkit-linear-gradient(top, #151515, #0a0a0a);
  background: -moz-linear-gradient(top, #151515, #0a0a0a);
  background: -o-linear-gradient(top, #151515, #0a0a0a);
  background: linear-gradient(to bottom, #151515, #0a0a0a);
  top: 0px;
  left: 0;
  border: 1px solid red;
}

答案 1 :(得分:-1)

.pageContent:first-child将匹配作为其容器的第一个子元素的.pageContent元素。在你的情况下它不起作用。

如果您想要第一个孩子,请尝试.pageContent > :first-child