Search code examples
csscss-selectorspseudo-class

Structural Pseudo Classes and attribute selectors doesn't work together


I have this HTML code :

<div class="field">                  
<input type="hidden" value="" name="a" id="a"> <input type="hidden" value="xxxx" name="b" id="b">
<input type="file" value="" name="file1"> <input type="file" value="" name="file2">
<input type="file" value="" name="file3"> <input type="file" value="" name="file4">
<input type="file" value="" name="file5"> <input type="file" value="" name="file6">
<input type="file" value="" name="file7"> <input type="file" value="" name="file8">     </div>

In this HTML, i want hide all input type="file" inside div class="field"except the first one. I cannot change the HTML (adding classes). I tried to apply a pseudoclasses and structurate selector toghether, to accomplish the task :

.field input[type='file']{
  display:none;
}

.field input[type='file']::first-child{
display:block;
}

But it seems doesn't work. Anyone could suggest me the right syntax for using pseudo classes and selector togheter in css, to solve this problem?


Solution

  • Pseudo-classes use only one colon, so it's :first-child, not ::first-child.

    But your first input[type='file'] is not the first child, so you can't use :first-child with it anyway.

    You have to switch the rules around and use a sibling selector instead to hide the subsequent file upload inputs:

    .field input[type='file'] {
        display:block;
    }
    
    .field input[type='file'] ~ input[type='file'] {
        display:none;
    }
    

    This technique is further described here, and can be used for most other simple selectors, not just classes and attributes.