CSS에서 요소에 포함된 하위 레벨 수를 감지할 수 있습니까?

6423 단어
Can CSS detect the number of children an element has?
I'm probably answering my own question, but I'm extremely curious. 나는 내 질문에 대답하고 있을지도 모르지만, 나는 매우 궁금하다.
I know that CSS can select individual children of a parent, but is there support to style the children of a container, if its parent has a certain amount of children. 나는 CSS가 부모 레벨의 각 하위 레벨을 선택할 수 있다는 것을 알고 있지만, 만약 부모 레벨이 일정한 수량의 하위 레벨이 있다면, 스타일링 용기의 하위 레벨을 지원할 수 있다.
for example 예:
container:children(8) .child {
  //style the children this way if there are 8 children
}

I know it sounds weird, but my manager asked me to check it out, haven't found anything on my own so I decided to turn to SO before ending the search. 이상하게 들리는 건 알지만 매니저가 검사를 해달라고 해서 아무것도 찾지 못했기 때문에 검색이 끝나기 전에 SO로 전환하기로 했습니다.
#1층
참조:https://stackoom.com/question/AAIb/CSS요소에 포함된 하위 레벨 수를 감지할 수 있습니까?
#2층
NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. 주의: 이 해결 방안은 당신이 요구하는 부모 요소가 아닌 일부 길이의 서브집합을 되돌려줍니다.Hopefully, it's still useful. 그것이 여전히 유용하기를 바란다.
Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/Unfortunately, it only works in IE9 and above. Andre Luis는 http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/불행히도 IE9 및 더 높은 버전에서만 유효합니다.
Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. 본질적으로: nth-child () 를 다른 처리 요소의 위치에 있는 위조 클래스와 조합합니다.This approach allows you to specify elements from sets of elements with specific lengths . 이 방법을 사용하면 특정 길이의 요소 세트에서 요소를 지정할 수 있습니다.
For instance :nth-child(1):nth-last-child(3) matches the first element in a set while also being the 3rd element from the end of the set. 예를 들어 :nth-child(1):nth-last-child(3)는 집합 중의 첫 번째 원소와 일치하며 집합 말미의 세 번째 원소이기도 하다.This does two things: guarantees that the set only has three elements and that we have the first of the three. 이것은 두 가지가 있다. 집합은 단지 세 개의 원소만 포함하고, 우리는 세 개의 원소 중 첫 번째 원소를 가지고 있다.To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2) . 세 개의 원소 집합의 두 번째 원소를 지정하려면 :nth-child(2):nth-last-child(2)을 사용할 것입니다.
Example 1 - Select all list elements if set has three elements: 예제 1 - set에 세 가지 요소가 있는 경우 모든 목록 요소를 선택합니다.
li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
    width: 33.3333%;
}

Example 1 alternative from Lea Verou: Lea Verou의 예 1 대안:
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

Example 2 - target last element of set with three list elements: 예제 2 - 세 가지 목록 요소를 사용하여 set의 마지막 요소를 찾습니다.
li:nth-child(3):last-child {
    /* I'm the last of three */
}

Example 2 alternative: 예 2의 대체 방법:
li:nth-child(3):nth-last-child(1) {
    /* I'm the last of three */
}

Example 3 - target second element of set with four list elements: 예제 3 - 네 개의 목록 요소를 포함하는 set의 두 번째 요소를 대상으로 사용합니다.
li:nth-child(2):nth-last-child(3) {
    /* I'm the second of four */
}

#3층
Clarification:맑음:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. 일부 SO 시민들은 원시적인 질문에 대한 이전 표현 때문에 이 답변에 대해 오해가 생길 수 있다는 우려를 제기했다.Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. CSS3에서는 스타일의 하위 레벨에 따라 상위 노드에 스타일을 적용할 수 없습니다.However, styles can be applied to the children nodes based on the number of siblings they have. 그러나 하위 노드가 가지고 있는 형제 노드 수에 따라 스타일을 하위 노드에 적용할 수 있다.
Original answer: 원래 답안:
Incredibly, this is now possible purely in CSS3. 이제 CS3에서 충분히 가능합니다.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. 비결은 첫 아이이자 n번째 아이일 때 첫 아이를 선택하는 것이다.This effectively selects based on the number of siblings. 이것은 효과적으로 형제자매의 수량에 따라 선택한다.
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined). 이런 기술은 칭찬할 만한 것이 André Luzis(발견)와 Lea Verou(정제)다.
Don't you just love CSS3? CSS3만 좋아하시는 거 아니에요?
CodePen Example: CodePen 예:
  • http://codepen.io/mattlubner/pen/RWPYdx http://codepen.io/mattlubner/pen/RWPYdx

  • Sources: 자료 출처:
  • http://andr3.net/blog/post/142 (André Luís) http://andr3.net/blog/post/142(안드레 루이스)
  • http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/(Lea Verou) http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/(Lea Verou)

  • #4층
    Working off of Matt's solution, I used the following Compass/SCSS implementation. Matt 기반 솔루션은 다음과 같은 Compass/SCSS를 사용하여 구현했습니다.
    @for $i from 1 through 20 {
        li:first-child:nth-last-child( #{$i} ),
        li:first-child:nth-last-child( #{$i} ) ~ li {
          width: calc(100% / #{$i} - 10px);
        }
      }
    

    This allows you to quickly expand the number of items. 이렇게 하면 항목 수를 빠르게 확장할 수 있습니다.
    #5층
    If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!! 순수 CSS(scss 사용)를 사용하여 이 작업을 진행하지만 같은 부류에 서로 다른 요소/클래스가 있다면 이 버전을 사용할 수 있습니다!
      &:first-of-type:nth-last-of-type(1) {
        max-width: 100%;
      }
    
      @for $i from 2 through 10 {
        &:first-of-type:nth-last-of-type(#{$i}),
        &:first-of-type:nth-last-of-type(#{$i}) ~ & {
          max-width: (100% / #{$i});
        }
      }
    

    #6층
    No, there is nothing like this in CSS. 아니오, CSS에는 유사한 것이 없습니다.You can, however, use JavaScript to calculate the number of children and apply styles. 하지만 JavaScript를 사용하여 하위 레벨을 계산하고 스타일을 적용할 수 있습니다.

    좋은 웹페이지 즐겨찾기