programing

: nth-child () 또는 : nth-of-type ()을 임의의 선택기와 결합 할 수 있습니까?

nasanasas 2020. 8. 18. 07:46
반응형

: nth-child () 또는 : nth-of-type ()을 임의의 선택기와 결합 할 수 있습니까?


임의의 선택자와 일치하는 (또는 일치하지 않는) 모든 n 번째 자식을 선택하는 방법이 있습니까? 예를 들어, 모든 홀수 테이블 행을 선택하지만 행의 하위 집합 내에서 선택하려고합니다.

table.myClass tr.row:nth-child(odd) {
  ...
}
<table class="myClass">
  <tr>
    <td>Row
  <tr class="row"> <!-- I want this -->
    <td>Row
  <tr class="row">
    <td>Row
  <tr class="row"> <!-- And this -->
    <td>Row
</table>

그러나 "row"클래스인지 여부에 관계없이 :nth-child()모든 tr요소 를 계산하는 것처럼 보이 므로 찾고있는 두 개 대신 하나의 "row"요소로 끝납니다 . 같은 일이 :nth-of-type().

누군가 이유를 설명 할 수 있습니까?


이것은 방법 :nth-child():nth-of-type()작업 에 대한 오해로 인해 발생하는 매우 일반적인 문제입니다 . 안타깝게도 현재 선택기 기반 솔루션은 없습니다. 선택자는 홀수, 짝수 또는 모든 an+b위치 a != 1위치 같은 패턴을 기반으로 임의의 선택자와 일치하는 n 번째 자식을 일치시키는 방법을 제공하지 않기 때문 b != 0입니다. 이것은 클래스 선택자뿐만 아니라 속성 선택자, 부정 및 단순한 선택 자의 더 복잡한 조합까지 확장됩니다.

:nth-child()의사 클래스 사이의 요소를 계산 모두 같은 부모 아래에서 자신의 형제를. 나머지 선택자와 일치하는 형제 만 계산하지 않습니다. 유사하게 유사 :nth-of-type()클래스 는 동일한 요소 유형을 공유하는 형제를 계산합니다. 이는 나머지 선택자가 아닌 HTML의 태그 이름을 참조합니다.

이것은 또한 같은 부모의 모든 경우 자녀는 자녀 테이블 본체의 경우, 예를 들어, 같은 요소 유형의 것을 의미 tr요소 나 어린이 만하는리스트 요소 li요소는 다음 :nth-child():nth-of-type()동일하게 동작합니다, 즉, 의 모든 값에 대해 an+b, :nth-child(an+b)그리고 :nth-of-type(an+b)요소의 동일한 세트를 일치합니다.

사실, 다음과 같은 가상 클래스를 포함하는 특정 화합물 선택기 모두 간단한 선택기, :nth-child():not()작업 독립적으로 서로, 오히려 찾고보다 일부 선택기의 나머지가 매칭 소자.

이는 또한 각 개별 화합물 선택자 1 내에서 단순 선택자간에 순서 개념이 없음 을 의미합니다. 즉, 예를 들어 다음 두 선택자가 동일하다는 것을 의미합니다.

table.myClass tr.row:nth-child(odd)
table.myClass tr:nth-child(odd).row

영어로 번역하면 둘 다 다음을 의미합니다.

다음의 모든 tr독립 조건과 일치 하는 요소를 선택하십시오 .

  • 부모의 홀수 번째 자식입니다.
  • 클래스 "row"가 있습니다.
  • table"myClass"클래스가 있는 요소 의 자손입니다 .

(여기에서 순서가 지정되지 않은 목록을 사용하는 것을 알 수 있습니다.

현재 순수한 CSS 솔루션이 없기 때문에 스크립트를 사용하여 요소를 필터링하고 그에 따라 스타일 또는 추가 클래스 이름을 적용해야합니다. 예를 들어 다음은 jQuery를 사용하는 일반적인 해결 방법입니다 ( tr테이블 내에 요소로 채워진 행 그룹이 하나만 있다고 가정 ).

$('table.myClass').each(function() {
  // Note that, confusingly, jQuery's filter pseudos are 0-indexed
  // while CSS :nth-child() is 1-indexed
  $('tr.row:even').addClass('odd');
});

해당 CSS 사용 :

table.myClass tr.row.odd {
  ...
}

Selenium과 같은 자동화 된 테스트 도구를 사용하거나 lxml과 같은 도구로 HTML을 처리하는 경우 이러한 도구 중 대부분은 XPath를 대안으로 허용합니다.

//table[contains(concat(' ', @class, ' '), ' myClass ')]//tr[contains(concat(' ', @class, ' '), ' row ')][position() mod 2)=1]

다른 기술을 사용하는 다른 솔루션은 독자에게 연습으로 남겨집니다. 이것은 단지 설명을위한 간단하고 인위적인 예입니다.


For what it's worth, there is a proposal for an extension to the :nth-child() notation to be added to Selectors level 4 for the specific purpose of selecting every nth child matching a given selector.2

The selector by which to filter matches is provided as an argument to :nth-child(), again due to how selectors operate independently of one another in a sequence as dictated by the existing selector syntax. So in your case, it would look like this:

table.myClass tr:nth-child(odd of .row)

(An astute reader will note right away that this ought to be :nth-child(odd of tr.row) instead, since the simple selectors tr and :nth-child() operate independently of one another as well. This is one of the problems with functional pseudo-classes that accept selectors, a can of worms I'd rather not open in the middle of this answer. Instead I'm going to go with the assumption that most sites will not have any other elements than tr elements as siblings of one another in a table body, which would make either option functionally equivalent.)

Of course, being a brand new proposal in a brand new specification, this probably won't see implementation until a few years down the road. In the meantime, you'll have to stick with using a script, as above.


1 If you specify a type or universal selector, it must come first. This does not change how selectors fundamentally work, however; it's nothing more than a syntactic quirk.

2 This was originally proposed as :nth-match(), however because it still counts an element relative only to its siblings, and not to every other element that matches the given selector, it has since as of 2014 been repurposed as an extension to the existing :nth-child() instead.


Not really..

quote from the docs

The :nth-child pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.

It is a selector of its own and does not combine with classes. In your rule it just has to satisfy both selector at the same time, so it will show the :nth-child(even) table rows if they also happen to have the .row class.


nth-of-type works according to the index of same type of the element but nth-child works only according to index no matter what type of siblings elements are.

For example

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>

Suppose in above html we want to hide all the elements having rest class.

In this case nth-child and nth-of-type will work exactly same as all the element are of same type that is <div> so css should be

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

OR

.rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
    display:none;
}

Now you must be wondering what is the difference between nth-child and nth-of-type so this is the difference

Suppose the html is

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>

In the above html the type of .rest element is different from others .rest are paragraphs and others are div so in this case if you use nth-child you have to write like this

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

but if you use nth-of-type css can be this

.rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
    display:none;
}

As type of .rest element is <p> so here nth-of-type is detecting the type of .rest and then he applied css on the 1st, 2nd, 3rd, 4th, 5th element of <p>.


You may be able to do that with xpath. something like //tr[contains(@class, 'row') and position() mod 2 = 0] might work. There are other SO questions expanding on the details how to match classes more precisely.


Here is your answer

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>TEST</title>

  <style>

    .block {
      background: #fc0;
      margin-bottom: 10px;
      padding: 10px;
    }
    /* .large > .large-item:nth-of-type(n+5) {
      background: #f00;
    } */

    .large-item ~ .large-item ~ .large-item ~ .large-item ~ .large-item {
      background: #f00;
    }

  </style>
</head>
<body>

<h1>Should be the 6th Hello Block that start red</h1>
<div class="small large">
  <div class="block small-item">Hello block 1</div>
  <div class="block small-item large-item">Hello block 2</div>
  <div class="block small-item large-item">Hello block 3</div>
  <div class="block small-item large-item">Hello block 4</div>
  <div class="block small-item large-item">Hello block 5</div>
  <div class="block small-item large-item">Hello block 6</div>
  <div class="block small-item large-item">Hello block 7</div>
  <div class="block small-item large-item">Hello block 8</div>
</div>

</body>
</html>

All of the questions around using nth-child and skipping hidden tags appear to be redirecting as dupes of this one so I will leave this here. I came across this blog https://blog.blackbam.at/2015/04/09/css-nth-child-selector-ignore-hidden-element/ that uses a clever css approach to make nth-child ignore hidden elements, as follows:

The following CSS adds a margin right to every second visible element no matter which element has the cpw class.

.cpw {
    display:none;
}

.video_prewrap {
    margin-right:20px;
}

.video_prewrap:nth-child(2n) {
    margin-right:0;
}

.cpw ~ .video_prewrap:nth-child(2n) {
    margin-right:20px;
}

.cpw ~ .video_prewrap:nth-child(2n-1) {
    margin-right:0;
}

Hope that helps someone who is following the dupe trail for the ignore hidden elements questions!

참고URL : https://stackoverflow.com/questions/5545649/can-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector

반응형