html - 使用 nth of type 或 nth-child 来定位元素?

标签 html css css-selectors

我有以下代码,我试图根据 .v-list 附加到它的类来选择四个 .v-list__tile p 元素之一,但没有成功使用 nth-child 或 nth -of-type 正确定位我想要的第一个元素。这是标记:

<div role="list" class="v-list theme--light price">
  <div role="listitem">
    <div class="v-list__tile theme--light">
      <p><strong>Price</strong></p>
    </div>
   </div>
  <div role="listitem">
    <div class="v-list__tile theme--light">
      <p><strong>Timing</strong></p>
    </div>
  </div>
  <div role="listitem">
    <div class="v-list__tile theme--light">
      <p><strong>Options</strong></p>
    </div>
  </div>
  <div role="listitem">
   <div class="v-list__tile theme--light">
    <p><strong>Review/Submit</strong></p>
   </div>
  </div>
 </div>

如果 .v-list 有一个“价格”类,我希望只有第一个 .v-list__tile p 元素附加样式。如果 .v-list 有一类“时间”,我希望仅第二个 .v-list__tile p 元素附加样式。这是我感到困惑的地方:我实际上能够选择所有除了第一个带有第 nth-child 的 p 元素,但是选择第一个 child 或第 nth-child(1) 会向 all 添加样式 的 p 个元素,而不仅仅是第一个。

.price div:nth-child(1) p{
   border-bottom:1px solid #009FD4; //doesn't work- selects *all* p elements//
 } 
.timing div:nth-child(2) p{
   border-bottom:1px solid #009FD4; //works- selects only the second p element//
 }
.options div:nth-child(3) p{
   border-bottom:1px solid #009FD4; //works- selects only the third p element//
 }
.review div:nth-child4) p{
   border-bottom:1px solid #009FD4; //works- selects only the fourth p element//
 }

我如何编写一些 css 以仅针对第一个 .v-list__tile p?

最佳答案

您是在告诉 css 在主 div .price 中查找所有 div。因为 .price 中的所有 div 都包含另一个子 div (v-list__tile),所以总会有第一个 div。当您定位第二个或第三个 child 时,因为在具有 Angular 色的 div 中没有第二个或第三个 div:listitem 那么这一切似乎都有效(但事实并非如此)。碰巧你的结构是这个结构,而你的结构末尾只有一个 div。 如果您只针对直系后代,您将能够实现您想要的目标:

.price > div:nth-child(1) p{
   border:1px solid #009FD4; 
 } 

希望这对您有所帮助:https://css-tricks.com/child-and-sibling-selectors/

关于html - 使用 nth of type 或 nth-child 来定位元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871698/

相关文章:

html - CSS:获取居中的流体图像背景

css - 在 OS X 中使用 USB 鼠标与无线/触控板时滚动条的外观不同

html - float 中心部分内的 CSS 部分

html - 如何使用非选择器为元素添加CSS

jquery - 删除 http ://localhost:8000/product/[object%20Object] 500 (Internal Server Error)

html - 无法使用 Bootstrap 对齐同一行中的图像

html - 将聊天箭头从左侧移动到右侧

javascript - 通过 Id 调用来遍历数组元素

c# - RegEx 仅从 CSS 文件中提取选择器?

html - 为子元素和父元素设置动画