Development Tip

클래스 "B"가 아닌 클래스 "A"가있는 div를 어떻게 선택합니까?

yourdevel 2021. 1. 7. 20:07
반응형

클래스 "B"가 아닌 클래스 "A"가있는 div를 어떻게 선택합니까?


몇 가지 div가 있습니다.

<div class="A">"Target"</div>
<div class="A B">"NotMyTarget"</div>
<div class="A C">"NotMyTarget"</div>
<div class="A D">"NotMyTarget"</div>
<div class="A E">"NotMyTarget"</div>

div를 포함 Target하지만 포함 하지 않는 div를 가져 오는 CSS 선택기가 NotMyTarget있습니까?

솔루션은 IE7, IE8, Safari, Chrome 및 Firefox에서 작동해야합니다.

편집 : 지금까지 Nick이 가장 가깝습니다. 서투르고 해결책이 마음에 들지 않지만 적어도 작동합니다.

.A
{
   /* style that all divs will take */
}
div.B 
{
  /* style that will override style .A */
}

속성 선택기를 사용하여 div클래스가 하나만 있는를 일치시킬 수 있습니다 .

div[class=A] {
  background: 1px solid #0f0;
}

div여러 클래스가있는 다른 클래스 를 선택 하려면 따옴표를 사용하십시오.

div[class="A C"] {
  background: 1px solid #00f;
}

일부 브라우저는 속성 선택기 구문을 지원하지 않습니다. 늘 그렇듯이 "일부 브라우저"는 IE 6 및 이전 버전의 완곡 어법입니다.

참조 : http://www.quirksmode.org/css/selector_attribute.html

전체 예 :

<!DOCTYPE html>
<html>
<head>
  <style>
    .A { font-size:22px; }
    .B { font-weight: bold; border: 1px solid blue; }
    .C { color: green; }

    div[class="A"] {
      border: 1px solid red;
    }
    div[class="A B"] {
      border: 3px solid green;
    }
  </style>
</head>
<body>
  <div class="A">"Target"</div> 
  <div class="A B">"NotMyTarget"</div> 
  <div class="A C">"NotMyTarget"</div> 
  <div class="A D">"NotMyTarget"</div> 
  <div class="A E">"NotMyTarget"</div> 
</body>
</html>

EDIT 2014-02-21: Four years later, :not is now widely available, though verbose in this specific case:

.A:not(.B):not(.C):not(.D):not(.E) {
  border: 1px solid red;
}

Unfortunately, this doesn't work in IE 7–8 as specified in the question: http://caniuse.com/#search=:not


.A:not(.B) {}

But guess who doesn't support that... Indeed, IE<=8.


I think the best you can do (until CSS 3) is override the styles in this case with what you don't want from class A B in A, like this:

.A.B { /* Styles */ }
.A { /* Reverse any styling you don't want */ }

ReferenceURL : https://stackoverflow.com/questions/2481414/how-do-i-select-a-div-with-class-a-but-not-with-class-b

반응형