: not (: empty) CSS 선택기가 작동하지 않습니까?


92

추가 :not(:empty)할 때 작동하지 않는이 특정 CSS 선택기로 시간을 보내고 있습니다. 다른 선택기의 조합으로 잘 작동하는 것 같습니다.

input:not(:empty):not(:focus):invalid { border-color: #A22; box-shadow: none }

:not(:empty)부품을 제거하면 잘 작동합니다. 선택기를 변경하더라도 input:not(:empty)텍스트가 입력 된 입력 필드는 선택되지 않습니다. 이것이 깨졌습니까 아니면 선택기 :empty내 에서 사용할 수 :not()없습니까?

내가 생각할 수있는 유일한 다른 것은 브라우저가 여전히 자식이 없기 때문에 요소가 비어 있다고 말하는 것입니다. 않는 :empty선택은 정기적 요소에 비해 입력 요소에 대해 별도의 기능을 가지고 있지? :empty필드에서 사용하고 여기 에 무언가를 입력하면 대체 효과가 사라지기 때문에 이것은 가능성이 없어 보입니다 (더 이상 비어 있지 않기 때문에).

Firefox 8 및 Chrome에서 테스트되었습니다.


관련 코드를 게시 할 수 있습니까?
— Virendra 2011

2
나는 당신의 일부가 인용 할 수 에 대한 API 참조 :empty선택기를 : "어떤 다른 요소를, 다른 한편으로는, 정의에 의해 (즉, 자녀가없는) 비어 : <input>, <img>, <br>, 및 <hr>, 예를 들어."
— David는 Monica를 복원한다고 말합니다.

@Virendra : 관련 코드이지만 실제 CSS 규칙을 추가했습니다. 를 제거하면 :not(:empty)초점이 맞지 않지만 유효하지 않은 입력에 대해 빨간색 테두리가 예상대로 작동합니다.
— animuson

답변:


149

수있는 Being 무효 요소 , <input>요소로 간주됩니다 빈 모든 무효 요소의 컨텐츠 모델 이후, "비우기"의 HTML 정의에 의해 항상 비어 있습니다 . 따라서 :empty값이 있는지 여부에 관계없이 항상 의사 클래스 와 일치합니다 . 이것이 그 값이 시작 및 끝 태그 내의 텍스트 내용이 아니라 시작 태그의 속성으로 표시되는 이유이기도합니다.

또한 선택기 사양에서 :

:empty의사 클래스는 모든에 자식이없는 요소를 나타냅니다. 문서 트리 측면에서 데이터 길이가 0이 아닌 요소 노드와 콘텐츠 노드 (예 : DOM 텍스트 노드, CDATA 노드 및 엔티티 참조) 만 비어 있음에 영향을 미치는 것으로 간주되어야합니다.

결과적으로 input:not(:empty)적절한 HTML 문서의 어떤 것과도 일치하지 않습니다. ( <input>텍스트 또는 자식 요소를 허용 할 수 있는 요소를 정의하는 가상의 XML 문서에서 여전히 작동 합니다.)

<input>CSS 만 사용하여 동적으로 빈 필드의 스타일을 지정할 수 있다고 생각하지 않습니다 (즉, 필드가 비어있을 때마다 적용되고 텍스트를 입력하지 않는 규칙). 속성 이 비어 있거나 ( ) 속성이 완전히없는 경우 ( ) 처음에 비어있는 필드를 선택할 수 있지만 그게 전부 입니다.valueinput[value=""]input:not([value])


흠, .NET으로 효과를 없애기 위해 무엇을했는지 기억이 나지 않습니다 input:empty. 내가 뭔가 잘못 입력했을 수도 있습니다.
— animuson

9
답변의 마지막 단락 에서 HTML 마크 업 input에서 required속성을 사용할 수 있다면 요소에 동적으로 스타일을 지정할 수 있습니다 (충분히 현대적인 브라우저에서) . 그런 다음 :valid및 :invalidCSS에서 컨트롤의 비어 있지 않은 값과 비어있는 값을 테스트 할 수 있습니다 . stackoverflow.com/questions/16952526/…
— Jukka K. Korpela

1
패턴 속성도 사용하지 않는 한 @ JukkaK.Korpela.
— WORMSS

2
input : not ([value = ''])은 값이있는 입력을 선택합니다;)
— Chris Love

@Chris Love : 초기 (페이지로드시) 값이있는 입력.
— BoltClock

43

인라인 자바 스크립트 onkeyup="this.setAttribute('value', this.value);"및input:not([value=""]):not(:focus):invalid

데모 : http://jsfiddle.net/mhsyfvv9/

input:not([value=""]):not(:focus):invalid{
  background-color: tomato;
}
<input 
  type="email" 
  value="" 
  placeholder="valid mail" 
  onchange="this.setAttribute('value', this.value);" />


하지 않 onchange이벤트는이 경우에 더 나은? Right click > Cut(예를 들어) 입력 값도 편집 할 수 있기 때문 입니다. 테스트 : 잘 작동합니다.
— Derk Jan Speelman

38

: placeholder-shown ...을 사용해 볼 수 있습니다.

input {
  padding: 10px 15px;
  font-size: 16px;
  border-radius: 5px;
  border: 2px solid lightblue;
  outline: 0;
  font-weight:bold;
  transition: border-color 200ms;
  font-family: sans-serif;
}

.validation {
  opacity: 0;
  font-size: 12px;
  font-family: sans-serif;
  color: crimson;
  transition: opacity;
}

input:required:valid {
  border-color: forestgreen;
}

input:required:invalid:not(:placeholder-shown) {
  border-color: crimson;
}

input:required:invalid:not(:placeholder-shown) + .validation {
  opacity: 1;
}

  
<input type="email" placeholder="e-mail" required>
<div class="validation">Not valid</span>

그래도 큰 지원은 ... caniuse


1
하지만 ... 꽤 좋은 지원 caniuse
— 레지 Pinkham

좋은 오래된 Internet Explorer (Y)
— rorymorris89

@ rorymorris89 EDGE의 최신 버전도 지원하지 않습니다. :-(
— Mo.

12

.floating-label-input {
  position: relative;
  height:60px;
}
.floating-label-input input {
  width: 100%;
  height: 100%;
  position: relative;
  background: transparent;
  border: 0 none;
  outline: none;
  vertical-align: middle;
  font-size: 20px;
  font-weight: bold;
  padding-top: 10px;
}
.floating-label-input label {
  position: absolute;
  top: calc(50% - 5px);
  font-size: 22px;
  left: 0;
  color: #000;
  transition: all 0.3s;
}
.floating-label-input input:focus ~ label, .floating-label-input input:focus ~ label, .floating-label-input input:valid ~ label {
  top: 0;
  font-size: 15px;
  color: #33bb55;
}
.floating-label-input .line {
  position: absolute;
  height: 1px;
  width: 100%;
  bottom: 0;
  background: #000;
  left: 0;
}
.floating-label-input .line:after {
  content: "";
  display: block;
  width: 0;
  background: #33bb55;
  height: 1px;
  transition: all 0.5s;
}
.floating-label-input input:focus ~ .line:after, .floating-label-input input:focus ~ .line:after, .floating-label-input input:valid ~ .line:after {
  width: 100%;
}
<div class="floating-label-input">
      <input type="text" id="id" required/>
      <label for="id" >User ID</label>
      <span class="line"></span>
</div>


7

이 방법은 다르게 접근 할 수 있습니다. 의 사용을 생략:empty의사 클래스input 이벤트를 활용 하여 <input>필드 에서 중요한 값을 감지하고 그에 따라 스타일을 지정합니다.

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  input.addEventListener('input', function() {
    var bg = this.value ? 'green' : 'red';
    this.style.backgroundColor = bg;
  });
}
body {
  padding: 40px;
}
#inputList li {
  list-style-type: none;
  padding-bottom: 1.5em;
}
#inputList li input,
#inputList li label {
  float: left;
  width: 10em;
}
#inputList li input {
  color: white;
  background-color: red;
}
#inputList li label {
  text-align: right;
  padding-right: 1em;
}
<ul id="inputList">
  <li>
    <label for="username">Enter User Name:</label>
    <input type="text" id="username" />
  </li>
  <li>
    <label for="password">Enter Password:</label>
    <input type="password" id="password" />
  </li>
</ul>

관련


면책 조항 : 참고input 이벤트는 현재 실험 단계 , 그리고 아마도 널리 지원되지 않습니다.


3

자리 표시자는 입력시 사라 지므로 다음을 사용할 수 있습니다.

input:placeholder-shown{
    //rules for not empty input
}

2

순수한 CSS 솔루션

input::-webkit-input-placeholder {
    opacity: 1;
    -webkit-transition: opacity 0s;
    transition: opacity 0s;
    text-align: right;
}
/* Chrome <=56, Safari < 10 */
input:-moz-placeholder {
    opacity: 1;
    -moz-transition: opacity 0s;
    transition: opacity 0s;
    text-align: right;
}
/* FF 4-18 */
input::-moz-placeholder {
    opacity: 1;
    -moz-transition: opacity 0s;
    transition: opacity 0s;
    text-align: right;
}
/* FF 19-51 */
input:-ms-input-placeholder {
    opacity: 1;
    -ms-transition: opacity 0s;
    transition: opacity 0s;
    text-align: right;
}
/* IE 10+ */
input::placeholder {
    opacity: 1;
    transition: opacity 0s;
    text-align: right;
}
/* Modern Browsers */

*:focus::-webkit-input-placeholder {
   opacity: 0;
   text-align: left;
}
/* Chrome <=56, Safari < 10 */
*:focus:-moz-placeholder {
    opacity: 0;
    text-align: left;
}
/* FF 4-18 */
*:focus::-moz-placeholder {
    opacity: 0;
    text-align: left;
}
/* FF 19-50 */
*:focus:-ms-input-placeholder {
    opacity: 0;
    text-align: left;
}
/* IE 10+ */
*:focus::placeholder {
    opacity: 0;
    text-align: left;
}
/* Modern Browsers */

input:focus {
    text-align: left;
}

0

또 다른 순수한 CSS 솔루션

.form{
  position:relative;
  display:inline-block;
}
.form input{
  margin-top:10px;
}
.form label{
    position:absolute;
    left:0;
    top:0;
    opacity:0;
    transition:all 1s ease;
}
input:not(:placeholder-shown) + label{
    top:-10px;
    opacity:1;
}
<div class="form">
    <input type="text" id="inputFName" placeholder="Firstname">
    <label class="label" for="inputFName">Firstname</label>
</div>
<div class="form">
    <input type="text" id="inputLName" placeholder="Lastname">
    <label class="label" for="inputLName">Lastname</label>
</div>


-1

이것은 최신 브라우저에서 작동합니다.

input[value]:not([value=""])

값 속성이있는 모든 입력을 선택한 다음 그 중에서 값이 비어 있지 않은 입력을 선택합니다.


10
그러나 이것은 동적이 아닙니다. 속성이로 정의 된 입력 요소 만 선택합니다 value="". 상자에 무언가를 입력 / 제거해도 변경 사항이 발생하지 않습니다.
— animuson

-1
input:not([value=""])

이것은 빈 문자열이 없을 때만 입력을 선택하기 때문에 작동합니다.


-1
input:not(:invalid){
 border: 1px red solid;
}

// or 

input:not(:focus):not(:invalid){
 border: 1px red solid;
}

1
10 개의 기존 답변이있는 11 년 된 질문에 답변을 추가 할 때 답변이 작동하는 방법과 이유에 대한 설명을 추가하고 답변이 다루는 질문의 새로운 측면을 지적하는 것이 정말 중요합니다. 질문을받은 이후로 변경된 내용에 따라 답변이 달라지는 경우에도이를 지적하십시오.
— Jason Aller
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.