我如何选择第二个列表的第一个li? [重复]

问题描述 投票:0回答:4

这是我正在使用的CSS类:

.list {
    flex-direction: column;
    align-items: inherit !important;
    width: 100%;
    display: inline-flex;
    border-bottom: none;
    text-decoration: none;
}

.list li {
    padding: 10px 0;
    display: flex;
    line-height: 1.4;
    padding-left: 0;
    border-bottom: #454b52 1px solid;
}

视图的HTML结构:

<ul class="list">
    <li></li>
    <li></li>
    <li></li>
</ul>
<ul class="list">
    <li></li>
    <li></li>
    <li></li>
</ul>

我想将第二个列表的第一个li定位为具有填充:0px 0px 10px用于移动设备和平板电脑视图。我尝试了这个选择器,但是它不起作用:

.list:nth-of-type(2) li:first-child{
    padding: 0px 0px 10px;
}
html css css-selectors html-lists
4个回答
0
投票

要选择第二个li中的第一个ul,您需要使用:nth-child css选择器。您可以在https://www.w3schools.com/cssref/sel_nth-child.asp中找到更多信息。

所以这是一个例子:

.list {
    flex-direction: column;
    align-items: inherit !important;
    width: 100%;
    display: inline-flex;
    border-bottom: none;
    text-decoration: none;
}

.list li {
    padding: 10px 0;
    display: flex;
    line-height: 1.4;
    padding-left: 0;
    border-bottom: #454b52 1px solid;
}

ul:nth-child(2) li:nth-child(1){
    border-bottom: red 1px solid;
}
<ul class="list">
    <li></li>
    <li></li>
    <li></li>
</ul>
<ul class="list">
    <li></li>
    <li></li>
    <li></li>
</ul>

0
投票

您不能选择id,class ... etcnth-*,但是在CSS中,您只能通过将标签名称<ul>作为选择器来使用,例如>

您可以这样操作:

ul:nth-of-type(2) li:first-of-type{
    /* your css properties here for the li */
}

Javascript

您可以使用javascript这样的代码:

elements = document.querySelectorAll('.list');
if (elements[1]) {
    // get first **li** 
    li = elements[1].firstElementChild;
    // try to change background color like this
    li.style.backgroundColor = "blue";
}

0
投票

您好,您的代码工作正常。要了解您通过.list:nth-​​of-type(2)li:first-child选择了正确的元素,我在li中使用了数字,并使用了红色。请检查以下代码:


-1
投票

ul包裹在div中>

<div>
  <ul class="list">
    <li></li>
    <li></li>
    <li></li>
  </ul>
  <ul class="list">
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.