developer tip

CSS 선택자가 아님

optionbox 2020. 11. 4. 07:54
반응형

CSS 선택자가 아님


CSS 선택자가 "아닌"종류가 있습니까?

예를 들어 CSS에 다음 줄을 작성할 때 classname 클래스있는 태그 내의 모든 입력 필드 는 빨간색 배경으로 표시됩니다.

.classname input {
  background: red;
}

classname 클래스를 사용하여 태그 외부에있는 모든 입력 필드를 어떻게 선택 합니까?



현재 브라우저 CSS 지원으로는 불가능합니다.

이제 최신 브라우저에서 지원 합니다. 자세한 내용은 Sam의 답변 을 참조하십시오.

(CSS의 대안에 대한 다른 답변을 참조하십시오.)


JavaScript / jQuery에서 수행하는 것이 허용되는 경우 다음을 수행 할 수 있습니다.

$j(':not(.classname)>input').css({background:'red'});

Mozilla는 부정 의사 클래스를 지원합니다 .

:not(.classname) input {background: red;}

참조 : http://developer.mozilla.org/en/Mozilla_CSS_support_chart


부정 의사 클래스는 선택기 레벨 3 권장 사항에 있으며 최신 버전의 Firefox, Chrome 및 Safari (적어도)에서 작동합니다. 아래 샘플 코드.

<html>
<head>
<title>Negation pseudo class</title>
<style type="text/css">
    div {
    border: 1px solid green;
    height: 10px;
    }
    div:not(#foo) {
    border: 1px solid red;
    }
</style>
</head>
<body>
    <div id="foo"></div>
    <div id="bar"></div>
    <div id="foobar"></div>
</body>
</html>

'전역'배경을 빨간색으로 설정 한 다음 클래스 이름을 사용하여 다른 배경을 변경하지 않겠습니까?

input { background: red; }
.classname input { background: white; }

나는 이것을 할 것이다

input { /* styles outside of .classname */ }
.classname input { /* styles inside of .classname, overriding above */ }

CSS와 일치하는 요소의 부모를 선택할 수있는 방법이 없습니다. 선택하려면 JavaScript를 사용해야합니다.

귀하의 질문에서 다음과 같이 보이는 마크 업이 있다고 가정합니다.

<form class="formclassname">
    <div class="classname">
        <input />  <!-- Your rule matches this -->
        <input />  <!-- Your rule matches this -->
    </div>
    <input />  <!-- You want to select this? -->
    <input />  <!-- You want to select this? -->
</form>

한 가지 옵션은 상위 요소 (예 :)에 클래스를 추가하고 <form>양식의 모든 입력에 스타일을 지정하는 규칙을 작성하는 것입니다. IE :

.formclassname input {
  /* Some properties here... */
}

또는

.formclassname > input {
  /* Some properties here... */
}

특정 클래스의 요소 내부에 있지 않다는 사실을 기반으로 선택하려는 경우 JavaScript를 사용하지 않고 운이 좋지 않습니다.


I think the closest you can get is to only affect direct descendants with a declaration

This code for example will only affect input fields directly under divs with class "maincontent"

div.maincontent > input {
  // do something
}

Inputs are a bit annoying because, unlike most other html elements, there isn't necessarily a way of resetting all the css properties back to their default value.

If the styling is non-critical (ie a nice to have but doesn't affect functionality) I would use jQuery to get an array of all the inputs, check their parents, and then only carry out the styling on those outside that div. Something like:

$('input').each(function() {
     if($(this).closest('.classname') == false)
     {
           // apply css styles
     }
});

(By the way, I'm no jQuery expert, so there might be some errors in the above, but in principle something like this should work)

참고URL : https://stackoverflow.com/questions/726493/not-css-selectors

반응형