如何修改伪元素HTML?实现点击滑块为.slider:before添加图文内容
Complete Toggle Slider with Custom Pseudo-Element Content
Got it, let's build that toggle slider you're working on—here's a full implementation that matches your requirements perfectly:
HTML Structure
First, a clean, accessible base structure using a checkbox input wrapped in a label:
<label class="toggle-container"> <input type="checkbox" class="toggle-input"> <div class="slider"></div> </label>
CSS Styling
Next, we'll style the slider and handle the pseudo-element's states. The magic happens when the slider is toggled—we inject centered text content into the ::before pseudo-element:
/* Base toggle container styles */ .toggle-container { position: relative; display: inline-block; width: 60px; height: 34px; } /* Hide the default checkbox */ .toggle-input { opacity: 0; width: 0; height: 0; } /* Slider track styles */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; } /* Default state: no content on the white slider knob */ .slider::before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; display: flex; align-items: center; justify-content: center; text-align: center; } /* Active state: add centered text to the white knob */ .toggle-input:checked + .slider::before { left: calc(100% - 26px - 4px); content: "A" "\A" "Sample"; white-space: pre-wrap; font-size: 16px; font-weight: bold; line-height: 1.2; } /* Optional: update track color when toggled on */ .toggle-input:checked + .slider { background-color: #2196F3; }
JavaScript (Alternative for Dynamic Control)
If you need to handle dynamic content or more complex logic later, you can swap the CSS :checked selector for a JavaScript class toggle:
const toggleInput = document.querySelector('.toggle-input'); const slider = document.querySelector('.slider'); toggleInput.addEventListener('change', () => { slider.classList.toggle('active'); });
Then update the CSS to target .slider.active::before instead of toggle-input:checked + .slider::before.
Quick Breakdown
- Flexbox on the pseudo-element ensures the text stays perfectly centered vertically and horizontally.
"\A"in thecontentproperty creates a line break, andwhite-space: pre-wrapmakes that break render properly.- Smooth transitions keep the toggle feeling polished, just like the example you referenced.
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

