etc./StackOverFlow

"이전 형제" 선택자가 있습니까?

청렴결백한 만능 재주꾼 2022. 2. 15. 08:50
반응형

질문자 :Jourkey


더하기 기호( + )는 다음 형제를 선택하기 위한 것입니다.

이전 형제와 동등한 것이 있습니까?



아니요, "이전 형제" 선택기가 없습니다.

관련 참고 사항에서 ~ 는 일반적인 후계자 형제를 위한 것이며(즉, 요소가 바로 뒤에 오는 것은 아니지만) CSS3 선택기입니다. + 는 다음 형제를 위한 것이며 CSS2.1입니다.

선택기 레벨 3의 인접 형제 결합자5.7 계단식 스타일 시트 레벨 2 개정 1(CSS 2.1) 사양의 인접 형제 선택자를 참조하십시오.


cletus

나는 당신이 필요로하는 것에 따라 작동 할 수있는 ~ 반대 )의 스타일을 지정하는 방법을 찾았습니다.

링크 목록이 있고 하나를 가리키면 이전 링크가 모두 빨간색으로 변해야 한다고 가정해 보겠습니다. 다음과 같이 할 수 있습니다.

 /* default link color is blue */ .parent a { color: blue; } /* prev siblings should be red */ .parent:hover a { color: red; } .parent a:hover, .parent a:hover ~ a { color: blue; }
 <div class="parent"> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> </div>


mantish

선택기 레벨 4에는 다음을 사용하여 이전 형제를 선택할 수 있는 :has() (이전에는 주제 표시기 !

 previous:has(+ next) {}

… 하지만 이 글을 쓰는 시점에서는 브라우저 지원을 위한 최첨단 기술을 넘어선 어느 정도 거리가 있습니다.


Quentin

플렉스 및 그리드 레이아웃 order 속성을 고려하십시오.

아래 예제에서 flexbox에 중점을 두겠지만 Grid에도 동일한 개념이 적용됩니다.


flexbox를 사용하면 이전 형제 선택자를 시뮬레이션할 수 있습니다.

특히 flex order 속성은 화면에서 요소를 이동할 수 있습니다.

다음은 예입니다.

요소 B를 가리키면 요소 A가 빨간색으로 바뀌기를 원합니다.

 <ul> <li>A</li> <li>B</li> </ul>

단계

  1. ul 을 플렉스 컨테이너로 만듭니다.

     ul { display: flex; }

  1. 마크업에서 형제의 순서를 반대로 합니다.

     <ul> <li>B</li> <li>A</li> </ul>

  1. 형제 선택기를 사용하여 요소 A를 대상으로 지정합니다( ~ 또는 + 가 수행함).

     li:hover + li { background-color: red; }

  1. order 속성을 사용하여 시각적 디스플레이에서 형제의 순서를 복원합니다.

     li:last-child { order: -1; }

...그리고 짜잔! 이전 형제 선택자가 태어납니다(또는 최소한 시뮬레이션됨).

전체 코드는 다음과 같습니다.

 ul { display: flex; } li:hover + li { background-color: red; } li:last-child { order: -1; } /* non-essential decorative styles */ li { height: 200px; width: 200px; background-color: aqua; margin: 5px; list-style-type: none; cursor: pointer; }
 <ul> <li>B</li> <li>A</li> </ul>

flexbox 사양에서:

5.4. 표시 순서: order 속성

Flex 항목은 기본적으로 소스 문서에 나타나는 것과 동일한 순서로 표시되고 배치됩니다. order 속성을 사용하여 이 순서를 변경할 수 있습니다.

order 속성은 플렉스 항목을 서수 그룹에 할당하여 플렉스 컨테이너 내에 나타나는 순서를 제어합니다. 플렉스 항목이 속한 서수 그룹을 지정하는 단일 <integer>

모든 플렉스 항목의 초기 order 값은 0입니다.

CSS 그리드 레이아웃 사양의 order 참조하십시오.


order 속성으로 생성된 "이전 형제 선택자"의 예.

 .container { display: flex; } .box5 { order: 1; } .box5:hover + .box4 { background-color: orangered; font-size: 1.5em; } .box6 { order: -4; } .box7 { order: -3; } .box8 { order: -2; } .box9 { order: -1; } .box9:hover ~ :not(.box12):nth-child(-1n+5) { background-color: orangered; font-size: 1.5em; } .box12 { order: 2; } .box12:hover ~ :nth-last-child(-1n+2) { background-color: orangered; font-size: 1.5em; } .box21 { order: 1; } .box21:hover ~ .box { background-color: orangered; font-size: 1.5em; } /* non-essential decorative styles */ .container { padding: 5px; background-color: #888; } .box { height: 50px; width: 75px; margin: 5px; background-color: lightgreen; display: flex; justify-content: center; align-items: center; text-align: center; cursor: pointer; }
 <p> Using the flex <code>order</code> property to construct a previous sibling selector </p> <div class="container"> <div class="box box1"><span>1</span></div> <div class="box box2"><span>2</span></div> <div class="box box3"><span>3</span></div> <div class="box box5"><span>HOVER ME</span></div> <div class="box box4"><span>4</span></div> </div> <br> <div class="container"> <div class="box box9"><span>HOVER ME</span></div> <div class="box box12"><span>HOVER ME</span></div> <div class="box box6"><span>6</span></div> <div class="box box7"><span>7</span></div> <div class="box box8"><span>8</span></div> <div class="box box10"><span>10</span></div> <div class="box box11"><span>11</span></div> </div> <br> <div class="container"> <div class="box box21"><span>HOVER ME</span></div> <div class="box box13"><span>13</span></div> <div class="box box14"><span>14</span></div> <div class="box box15"><span>15</span></div> <div class="box box16"><span>16</span></div> <div class="box box17"><span>17</span></div> <div class="box box18"><span>18</span></div> <div class="box box19"><span>19</span></div> <div class="box box20"><span>20</span></div> </div>

jsFiddle


참고 사항 - CSS에 대한 두 가지 오래된 믿음

Flexbox는 CSS에 대한 오랜 신념을 깨고 있습니다.

그러한 믿음 중 하나 는 이전 형제 선택자가 CSS에서 가능하지 않다는 것 입니다.

이 믿음이 널리 퍼져 있다고 말하는 것은 과소 평가가 될 것입니다. 다음은 스택 오버플로에 대한 관련 질문의 샘플입니다.

위에서 설명한 것처럼 이 믿음은 완전히 사실이 아닙니다. order 속성을 사용하여 CSS에서 시뮬레이션할 수 있습니다.

z-index 오해

또 다른 오랜 믿음은 z-index 가 위치 지정 요소에서만 작동한다는 것입니다.

사실, 사양의 가장 최신 버전인 W3C Editor's Draft 는 여전히 이것이 사실이라고 주장합니다.

9.9.1 스택 레벨 지정: z-index 속성

z-index

  • 값: 자동 | | 상속하다
  • 이니셜: 자동
  • 적용 대상: 위치 지정 요소
  • 상속: 아니요
  • 백분율: N/A
  • 미디어: 비주얼
  • 계산된 값: 지정된 대로

(강조 추가됨)

그러나 실제로 이 정보는 쓸모없고 정확하지 않습니다.

가변 항목 또는 그리드 항목인 요소는 positionstatic 경우에도 스택 컨텍스트를 생성할 수 있습니다.

4.3. 플렉스 아이템 Z-주문

Flex 항목은 원시 문서 순서 대신 order-modified document order가 사용되고 positionstatic auto 이외의 z-index 값이 스택 컨텍스트를 생성한다는 점을 제외하고 인라인 블록과 정확히 동일하게 페인트됩니다.

5.4. Z축 정렬: z-index 속성

그리드 항목의 페인팅 순서는 원시 문서 순서 대신 순서 수정 문서 순서가 사용되고 positionstatic auto 이외의 z-index 값이 스택 컨텍스트를 생성한다는 점을 제외하면 인라인 블록과 정확히 동일합니다.

다음은 위치가 지정되지 않은 플렉스 항목에서 작동하는 z-index 의 데모입니다 . https://jsfiddle.net/m0wddwxs/


Michael Benjamin

나는 같은 질문을 가졌으나 그때 나는 "어" 순간을 가졌다. 쓰는 대신

 x ~ y

쓰다

 y ~ x

분명히 이것은 "y" 대신 "x"와 일치하지만 "일치하는 항목이 있습니까?"라고 대답합니다. 질문과 간단한 DOM 순회는 자바스크립트에서 반복하는 것보다 더 효율적으로 올바른 요소로 이동할 수 있습니다.

나는 원래 질문이 CSS 질문이라는 것을 알고 있으므로 이 대답은 아마도 완전히 관련이 없지만 다른 Javascript 사용자는 나처럼 검색을 통해 질문을 우연히 발견할 수 있습니다.


Bryan Larsen

+ 는 다음 형제를 위한 것입니다. 이전 형제와 동등한 것이 있습니까?

두 개의 도끼 선택기를 사용할 수 있습니다 ! 그리고 ?

2개의 후속 형제 선택자가 있습니다.


Community Wiki

두 가지 트릭 . 기본적으로 HTML에서 원하는 요소의 HTML 순서를 반전하고
~ 다음 형제 연산자:

float-right + HTML 요소의 역순

 div{ /* Do with the parent whatever you know just to make the inner float-right elements appear where desired */ display:inline-block; } span{ float:right; /* float-right the elements! */ } span:hover ~ span{ /* On hover target it's "previous";) elements */ background:red; }
 <div> <!-- Reverse the order of inner elements --> <span>5</span> <span>4</span> <span>3</span> <span>2</span> <span>1</span> </div>


direction: rtl; 부모: rtl; + 내부 요소의 역순

 .inverse{ direction: rtl; display: inline-block; /* inline-block to keep parent at the left of window */ } span:hover ~ span{ /* On hover target it's "previous";) elements */ background:gold; }
 Hover one span and see the previous elements being targeted!<br> <div class="inverse"> <!-- Reverse the order of inner elements --> <span>5</span> <span>4</span> <span>3</span> <span>2</span> <span>1</span> </div>


Roko C. Buljan

"이전 선택기"는 없지만 :not~ ("선택기 이후")의 조합을 사용할 수 있습니다. 역순도 없고 자바스크립트도 없습니다.

 .parent a{ color: blue } .parent a.active{ color: red } .parent a:not(.parent a.active ~ a){ color: red }
 <div class="parent"> <a href="">link</a> <a href="">link</a> <a href="" class="active">link</a> <a href="">link</a> <a href="">link</a> </div>

내 접근 방식은 "모든 div 스타일 지정, div 이후 스타일 제거", 자바 스크립트 사용 또는 역순 사용보다 더 간단합니다.


Victor Gorban

또 다른 플렉스박스 솔루션

HTML에서 요소의 역순을 사용할 수 있습니다. 그런 다음 Michael_B의 답변 에서와 같이 order 를 사용하는 것 외에도 flex-direction: row-reverse; 사용할 수 있습니다. 또는 flex-direction: column-reverse; 레이아웃에 따라.

작업 샘플:

 .flex { display: flex; flex-direction: row-reverse; /* Align content at the "reversed" end ie beginning */ justify-content: flex-end; } /* On hover target its "previous" elements */ .flex-item:hover ~ .flex-item { background-color: lime; } /* styles just for demo */ .flex-item { background-color: orange; color: white; padding: 20px; font-size: 3rem; border-radius: 50%; }
 <div class="flex"> <div class="flex-item">5</div> <div class="flex-item">4</div> <div class="flex-item">3</div> <div class="flex-item">2</div> <div class="flex-item">1</div> </div>


Vadim Ovchinnikov

현재로서는 공식적인 방법이 없지만 이를 달성하기 위해 약간의 트릭을 사용할 수 있습니다! 실험적이며 몇 가지 제한 사항이 있음을 기억하십시오 ... (내비게이터 호환성이 걱정되는 경우이 링크를 확인하십시오)

할 수 있는 일은 CSS3 선택기를 사용하는 것입니다. nth-child()

 #list>* { display: inline-block; padding: 20px 28px; margin-right: 5px; border: 1px solid #bbb; background: #ddd; color: #444; margin: 0.4em 0; } #list :nth-child(-n+4) { color: #600b90; border: 1px dashed red; background: orange; }
 <p>The oranges elements are the previous sibling li selected using li:nth-child(-n+4)</p> <div id="list"> <span>1</span><!-- this will be selected --> <p>2</p><!-- this will be selected --> <p>3</p><!-- this will be selected --> <div>4</div><!-- this will be selected --> <div>5</div> <p>6</p> <p>7</p> <p>8</p> <p>9</p> </div>

제한 사항

  • 다음 요소의 클래스를 기반으로 이전 요소를 선택할 수 없습니다.
  • 이것은 의사 클래스에서도 동일합니다.

0x1gene

이중 부정을 사용할 수 있습니다.

 SELECTOR:not([SELECTOR]FILTER):not([SELECTOR]FILTER + SELECTOR) { ... }

교체 SELECTOR 중 하나와 TAG 또는 .CLASS (사용 #ID 너무 아마 다릅니다). FILTER 를 다른 :PSUEDO-SELECTOR :hover 만 시도했습니다) 또는 .CLASS (Javascript를 통한 토글에 대한 추가 정보)로 교체합니다.

일반적인 사용법은 아마도 호버링에 의존할 것이기 때문에(다음 예 참조)

 /* Effect only limited when hovering */ TAG.CLASS:not(TAG.CLASS:hover):not(TAG.CLASS:hover + TAG.CLASS) {} /* Effect only applied when hovering */ PARENT.CLASS:hover > CHILD.CLASS:not(CHILD.CLASS:hover):not(CHILD.CLASS:hover + CHILD.CLASS) {} 

 /* Solution */ div.parent:hover > div.child:not(:hover):not(:hover ~ .child) { background-color:red; border-radius:1.5em; } div.parent:hover > div.child:not(:hover):not(:hover ~ .child) > div { background-color:yellow; } /* Make pretty (kinda) */ div.parent { width:9em; height:9em; /* Layout */ display:grid; grid-template-columns : auto auto auto; grid-template-rows : auto auto auto; } div.child { /* Dimensions */ height:3em; width:3em; /* Layout */ position:relative; /* Cursor */ cursor: pointer; /* Presentation */ border: 1px black solid; border-radius:1.5em; } .star { /* Dimensions */ width: 2.5em; height: 2.5em; /* Placement */ position:absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); /* Geometry */ -webkit-clip-path: polygon( 50% 0%, 63% 38%, 100% 38%, 69% 59%, 82% 100%, 50% 75%, 18% 100%, 31% 59%, 0% 38%, 37% 38% ); clip-path: polygon( 50% 0%, 63% 38%, 100% 38%, 69% 59%, 82% 100%, 50% 75%, 18% 100%, 31% 59%, 0% 38%, 37% 38% ); /* Presentation */ background-color: lightgrey; } div.child:hover { /* Presentation */ background-color:yellow; border-radius:1.5em; } div.child:hover > div.star { /* Presentation */ background-color:red; }
 <div class="parent"> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> <div class="child" href="#"><div class="star"></div></div> </div>


Carel

아니요. CSS를 통해서는 불가능합니다. 그것은 마음에 "캐스케이드"를 걸립니다 ;-).


그러나 페이지에 JavaScript 를 추가할 수 있다면 약간의 jQuery 가 최종 목표에 도달할 수 있습니다.
jQuery의 find 를 사용하여 대상 요소/클래스/id에 대해 "미리보기"를 수행한 다음 역추적하여 대상을 선택할 수 있습니다.
그런 다음 jQuery를 사용하여 요소에 대한 DOM(CSS)을 다시 작성합니다.

Mike Brant의 이 답변을 바탕으로 다음 jQuery 스니펫이 도움이 될 수 있습니다.

 $('p + ul').prev('p')

이것은 먼저 <p> 바로 다음에 오는 <ul> 선택합니다.
<ul> 세트에서 <p> 를 선택하기 위해 "역추적"합니다.

효과적으로 "이전 형제"는 jQuery를 통해 선택되었습니다.
.css 함수를 사용하여 해당 요소에 대한 CSS 새 값을 전달합니다.


#full-width 인 DIV를 선택하는 방법을 찾고 .companies 클래스의 (간접) 하위 DIV가 있는 경우에만 가능합니다.

.companies 아래의 모든 HTML을 제어할 수 있었지만 그 위의 HTML을 변경할 수는 없었습니다.
그리고 캐스케이드는 아래로 한 방향으로만 진행됩니다.

따라서 ALL #full-width s를 선택할 수 있습니다.
#full-width 만 뒤에 오는 .companies 를 선택할 수 있습니다.
그러나 나는 단지 선택하지#full-width 진행의 .companies .

그리고 다시 HTML에서 상위 .companies 를 추가할 수 없었습니다. HTML의 해당 부분은 외부에서 작성되었으며 코드를 래핑했습니다.

그러나 jQuery를 함께, 내가 필요한 선택할 수 있습니다 #full-width 들, 다음 적절한 스타일을 지정합니다 :

 $("#full-width").find(".companies").parents("#full-width").css( "width", "300px" );

이것은 모든 #full-width .companies 선택기가 CSS에서 표준의 특정 요소를 대상으로 지정하는 데 사용되는 것과 유사한 .companies 만 선택합니다.
그런 다음 .parents 를 사용하여 "역추적"하고 .companies 모든 부모를 선택합니다.
하지만 결과를 필터링하여 #fill-width 요소만 유지하므로 결국
.companies 클래스 자손이 있는 경우 #full-width 요소를 선택합니다.
마지막으로 결과 요소에 새 CSS( width

 $(".parent").find(".change-parent").parents(".parent").css( "background-color", "darkred");
 div { background-color: lightblue; width: 120px; height: 40px; border: 1px solid gray; padding: 5px; } .wrapper { background-color: blue; width: 250px; height: 165px; } .parent { background-color: green; width: 200px; height: 70px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <div class="wrapper"> <div class="parent"> "parent" turns red <div class="change-parent"> descendant: "change-parent" </div> </div> <div class="parent"> "parent" stays green <div class="nope"> descendant: "nope" </div> </div> </div> Target <b>"<span style="color:darkgreen">parent</span>"</b> to turn <span style="color:red">red</span>.<br> <b>Only</b> if it <b>has</b> a descendant of "change-parent".<br> <br> (reverse cascade, look ahead, parent un-descendant) </html>

jQuery 참조 문서:
$() 또는 jQuery() : DOM 요소.
. find : 선택기, jQuery 객체 또는 요소로 필터링된 현재 일치하는 요소 집합에서 각 요소의 하위 항목을 가져옵니다.
. 부모 : 일치하는 요소 집합에서 각 요소의 바로 앞 형제를 가져옵니다. 선택기가 제공되면 해당 선택기와 일치하는 경우에만 이전 형제를 검색합니다(나열된 요소/선택기만 포함하도록 결과를 필터링함).
. css : 일치하는 요소 집합에 대해 하나 이상의 CSS 속성을 설정합니다.


SherylHohman

정확한 위치를 알고 있다면 :nth-child() 기반의 다음 형제 모두 제외가 작동합니다.

 ul li:not(:nth-child(n+3))

3번째(예: 1번째 및 2번째) 이전의 li 선택합니다. 그러나 제 생각에는 이것은 보기 흉하고 매우 빡빡한 사용 사례를 가지고 있습니다.

오른쪽에서 왼쪽으로 n번째 자식을 선택할 수도 있습니다.

 ul li:nth-child(-n+2)

동일한 작업을 수행합니다.


kernel

호버에서 다음 형제의 스타일을 제거하여 이전 형제만 가리키면 스타일이 추가된 것처럼 보입니다.

 ul li { color: red; cursor: pointer; } ul:hover li { color: blue; } ul:hover li:hover ~ li{ color: red; }
 <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul>


Megha

불행히도 "이전" 형제 선택자는 없지만 위치 지정(예: float right)을 사용하여 여전히 동일한 효과를 얻을 수 있습니다. 그것은 당신이하려는 일에 달려 있습니다.

제 경우에는 주로 CSS 5-스타 등급 시스템을 원했습니다. 이전 별에 색상을 지정하거나 아이콘을 교체해야 합니다. 각 요소를 오른쪽으로 띄우면 본질적으로 동일한 효과를 얻을 수 있습니다(따라서 별에 대한 html은 '뒤집어'로 작성해야 함).

이 예제에서 FontAwesome을 사용하고 fa-star-o와 fa-star의 유니코드를 교환하고 있습니다. http://fortawesome.github.io/Font-Awesome/

CSS:

 .fa { display: inline-block; font-family: FontAwesome; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /* set all stars to 'empty star' */ .stars-container { display: inline-block; } /* set all stars to 'empty star' */ .stars-container .star { float: right; display: inline-block; padding: 2px; color: orange; cursor: pointer; } .stars-container .star:before { content: "\f006"; /* fontAwesome empty star code */ } /* set hovered star to 'filled star' */ .star:hover:before{ content: "\f005"; /* fontAwesome filled star code */ } /* set all stars after hovered to'filled star' ** it will appear that it selects all after due to positioning */ .star:hover ~ .star:before { content: "\f005"; /* fontAwesome filled star code */ }

HTML: (40)

JSFiddle: http://jsfiddle.net/andrewleyva/88j0105g/


Andrew Leyva

정확한 목적에 따라 부모 선택자를 사용하지 않고 (존재하더라도) 부모 선택자의 유용성을 달성하는 방법이 있습니다.

우리가 가지고 있다고 가정해 봅시다:

 <div> <ul> <li><a>Pants</a></li> <li><a>Socks</a></li> <ul> <li><a>White socks</a></li> <li><a>Blue socks</a></li> </ul> </ul> </div>

간격을 사용하여 양말 블록(양말 색상 포함)을 시각적으로 돋보이게 하려면 어떻게 해야 합니까?

좋겠지만 존재하지 않는 것:

 ul li ul:parent { margin-top: 15px; margin-bottom: 15px; }

존재하는 것:

 li > a { margin-top: 15px; display: block; } li > a:only-child { margin-top: 0px; }

이렇게 하면 모든 앵커 링크가 상단에 15px 여백을 갖도록 설정하고 LI 내부에 UL 요소(또는 다른 태그)가 없는 링크에 대해 다시 0으로 재설정합니다.


DynamicDan

이전 형제 tr을 선택하는 솔루션이 필요했습니다. 나는 React와 Styled-components를 사용하여 이 솔루션을 생각해 냈습니다. 이것은 나의 정확한 해결책이 아닙니다(이것은 몇 시간 후의 기억에서 나온 것입니다). setHighlighterRow 함수에 결함이 있다는 것을 알고 있습니다.

OnMouseOver a 행은 행 인덱스를 상태로 설정하고 이전 행을 새로운 배경색으로 다시 렌더링합니다.

 class ReactClass extends Component { constructor() { this.state = { highlightRowIndex: null } } setHighlightedRow = (index) => { const highlightRowIndex = index === null ? null : index - 1; this.setState({highlightRowIndex}); } render() { return ( <Table> <Tbody> {arr.map((row, index) => { const isHighlighted = index === this.state.highlightRowIndex return { <Trow isHighlighted={isHighlighted} onMouseOver={() => this.setHighlightedRow(index)} onMouseOut={() => this.setHighlightedRow(null)} > ... </Trow> } })} </Tbody> </Table> ) } } const Trow = styled.tr` & td { background-color: ${p => p.isHighlighted ? 'red' : 'white'}; } &:hover { background-color: red; } `;

kyle

없다, 그리고있다.

당신이 입력하기 전에 레이블을 배치해야합니다, 그냥 입력라벨을 배치하고 라벨사업부 내부의 입력 및 스타일 다음과 같이 사업부 모두 유지 :

 .input-box { display: flex; flex-direction: column-reverse; }
 <div class="input-box"> <input id="email" class="form-item" /> <label for="email" class="form-item-header"> E-Mail* </label> </div>

이제 CSS에서 사용할 수 있는 표준 다음 형제 스타일 옵션을 적용할 수 있으며 이전 형제 스타일을 사용하는 것처럼 나타납니다.


Ron16

 /* Add a style to all the children, then undo the style to the target and sibling children of your target. */ ul>li { color: red; } ul>li.target, ul>li.target~li { color: inherit; }
 <ul> <li>before</li> <li class="target">target</li> <li>after</li> <li>after</li> </ul>


Nando

나는 비슷한 문제가 있었고 이러한 성격의 모든 문제는 다음과 같이 해결할 수 있음을 알았습니다.

  1. 모든 항목에 스타일을 부여하십시오.
  2. 선택한 항목에 스타일을 부여하십시오.
  3. + 또는 ~를 사용하여 다음 항목에 스타일을 지정합니다.

이렇게 하면 현재, 이전 항목(모든 항목이 현재 및 다음 항목으로 재정의됨) 및 다음 항목의 스타일을 지정할 수 있습니다.

예시:

 /* all items (will be styled as previous) */ li { color: blue; } /* the item i want to distinguish */ li.milk { color: red; } /* next items */ li ~ li { color: green; } <ul> <li>Tea</li> <li class="milk">Milk</li> <li>Juice</li> <li>others</li> </ul>

누군가를 돕기를 바랍니다.


Hejar

여기에 비슷한 질문에 대한 링크가 있습니다

CSS는 별 등급에 대해 모든 이전 형제를 선택합니다.

그래서 나는 모든 사람의 응답을 사용하여 내 솔루션을 게시하고 누구나 참조로 사용할 수 있으며 개선을 권장할 수 있습니다.

 // Just to check input value // Consts const starRadios = document.querySelectorAll('input[name="rating"]'); // EventListeners starRadios.forEach((radio) => radio.addEventListener('change', getStarRadioValue)); // Get star radio value function getStarRadioValue(event) { alert(event.target.value) // Do something with it };
 .star-rating { font-size: 1.5rem; unicode-bidi: bidi-override; direction: rtl; text-align: left; } .star-rating.editable label:hover { cursor: pointer; } .star-rating.editable .icon-star:hover, .star-rating.editable .icon-star:hover ~ .icon-star { background-color: #fb2727 !important; } .icon-star { position: relative; background-color: #72747d; width: 32px; height: 32px; display: inline-block; transition: background-color 0.3s ease; } .icon-star.filled { background-color: #fb2727; } .icon-star > label { display: inline-block; width: 100%; height: 100%; left: 0; top: 0; position: absolute; } .icon-star > label > input[type="radio"] { position: absolute; top: 0; left: 0; transform: translateY(50%) translateX(50%); display: none; }
 <div class="star-rating editable"> <span class="icon-star"> <label> <input type="radio" name="rating" value="5" /> </label> </span> <span class="icon-star"> <label> <input type="radio" name="rating" value="4" /> </label> </span> <span class="icon-star"> <label> <input type="radio" name="rating" value="3" /> </label> </span> <span class="icon-star"> <label> <input type="radio" name="rating" value="2" /> </label> </span> <span class="icon-star"> <label> <input type="radio" name="rating" value="1" /> </label> </span> </div>


Jackal

그러한 선택기는 없지만 DOM API에는 읽기 전용 속성이 있습니다.

Node.previousSibling


Dmitry G. Anderson

가장 쉬운 해결책을 찾았습니다. 그것은 당신이하는 일을 기반으로 만 적용될 수 있습니다.

아래 예에서 "sibling_1"을 변경하기 위해 "sibling_2"를 가리키고 싶다고 가정해 보겠습니다.

 <div class='parent'> <div class='sibling_1'></div> <div class='sibling_2'></div> </div>

이전 요소 선택기가 없으므로 'sibling_1'과 'sibling_2'를 전환하고 적용하여 동일하게 보이도록 할 수 있습니다.

 .parent { display: flex; flex-direction: row-reverse; }

이제 그런 식으로 선택할 수 있습니다.

 .sibling_1:hover ~ .sibling_2 { #your CSS }


Roma Kim

나는 이와 같은 문제가 있었지만 입력 포커스에서 아이콘 채우기 색상을 변경하려고 시도하는 동안 내 코드는 다음과 같았습니다.

 <template #append> <b-input-group-text><strong class="text-danger">!</strong></b-input-group-text> </template> <b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

문제는 vue-bootstrap 슬롯 을 사용하여 접두어를 삽입하고 있으므로 위치를 변경하더라도 입력 후에 여전히 렌더링된다는 것입니다.

내 솔루션은 위치를 스 와이프하고 CSS가 이전 형제를 지원하지 않기 때문에 사용자 정의 앞에 추가하고 ~ 기호를 사용하는 것이 었습니다.

 <div class="form-input-prepend"> <svg-vue icon="common.lock" /> </div> <b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

CSS 스타일

 .form-control:focus ~ .form-input-prepend { svg path { fill: $accent; } }

따라서 위치를 변경하려고 시도하고 필요한 경우 css order 또는 position: absolute; 원하는 것을 달성하고 이러한 종류의 요구에 자바 스크립트를 사용하지 마십시오.


AbdessamadEL

출처 : http:www.stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector

반응형