CSS相邻兄弟选择器针对disabled文件输入框失效问题求助
Hey there! The problem you're facing is that your CSS selector isn't targeting the custom-file-upload label correctly. Let's break down why, then walk through a few straightforward solutions.
Why It's Not Working
Your current CSS uses the adjacent sibling selector (+):
.btn-file input[type="file"]:disabled+.custom-file-upload { opacity: 0.5; }
This selector looks for a .custom-file-upload element that directly follows a disabled input[type="file"]. But in your HTML structure, the label (with the .custom-file-upload class) comes before the input element. CSS selectors can't target elements that come earlier in the DOM, so your styles never get applied.
Solution 1: Adjust HTML Structure (Simplest Fix)
If you can rearrange your HTML to put the input before the label, your original CSS will work perfectly:
<div class="btn-file"> <input type="file" id="FileUpload1" class="" disabled=""> <label for="FileUpload1" class="custom-file-upload"> <i class="fa fa-upload"></i> Upload Logo </label> </div>
Now the disabled input is directly followed by the .custom-file-upload label, so the adjacent sibling selector will correctly apply the opacity (you can add a background-color rule here too if you want to change the button's color).
Solution 2: Use CSS :has() Selector (No HTML Changes, Modern Browsers)
If you don't want to modify your HTML, use the CSS :has() pseudo-class to target the parent .btn-file element when it contains a disabled file input, then style the label:
.btn-file:has(input[type="file"]:disabled) .custom-file-upload { opacity: 0.5; background-color: #ccc; /* Replace with your desired disabled background color */ }
Note: :has() works in all modern browsers (Chrome, Firefox 121+, Edge, Safari), but won't support older browsers like IE.
Solution 3: JavaScript Fallback (For Older Browser Compatibility)
If you need to support older browsers that don't have :has() support, use JavaScript to add a class to the parent element when the input is disabled, then style based on that class:
JavaScript:
const fileInput = document.getElementById('FileUpload1'); // Set initial disabled state if (fileInput.disabled) { fileInput.parentElement.classList.add('file-input-disabled'); } // Update state if the input's disabled status changes dynamically fileInput.addEventListener('change', function() { this.parentElement.classList.toggle('file-input-disabled', this.disabled); });
Add This CSS:
.btn-file.file-input-disabled .custom-file-upload { opacity: 0.5; background-color: #ccc; /* Your preferred disabled background color */ }
内容的提问来源于stack exchange,提问作者Muhammad Awais Iqbal

