这里是CSS网格的一个想法,诀窍是将两个元素放在同一个区域内。您还可以保持相同的HTML结构。
相关代码:
.switchToggle {
...
display: grid;
align-items:center;
...
}
.switchToggle > * {
grid-area:1/1;
}
.switchToggleValue--on {
padding-right:32px;
}
.switchToggleValue--off {
padding-left:32px;
text-align:right;
}
完整代码:
.switch {
display: inline-block;
position: relative;
margin:5px;
}
.switchInput {
cursor: pointer;
height: 100%;
opacity: 0;
position: absolute;
width: 100%;
z-index: 1;
}
.switchToggle {
background-color: #9a3d37;
border-radius: 50px;
display: grid;
align-items:center;
height: 24px;
position: relative;
transition: background-color ease-out 0.3s;
z-index: 0;
}
.switchToggle > * {
grid-area:1/1;
}
.switchToggleValue--on {
padding-right:32px;
}
.switchToggleValue--off {
padding-left:32px;
text-align:right;
}
.switchToggle:before {
content: "";
background: #fff;
box-shadow: 1px 0 2px #646464;
border-radius: 50%;
border: 1px solid #aaaaaa;
height: 24px;
left: 0;
position: absolute;
top: 0;
transition: 0.2s ease-out;
width: 24px;
z-index: 2;
}
.switchToggleValue {
text-transform: uppercase;
line-height: normal;
transition: opacity 0.2s ease-out 0.1s;
}
.switchToggleValue--on {
margin: 0 4px 0 8px;
opacity: 0;
}
.switchToggleValue--off {
margin: 0 8px 0 4px;
opacity: 1;
}
.switchInput:checked ~ .switchToggle {
background-color: #6a7d39;
}
.switchInput:checked ~ .switchToggle:before {
left: calc(100% - 24px);
box-shadow: -1px 0 2px #646464;
}
.switchInput:checked ~ .switchToggle .switchToggleValue--on {
opacity: 1;
}
.switchInput:checked ~ .switchToggle .switchToggleValue--off {
opacity: 0;
}
.switchLabel {
margin-left: 15px;
}
<div class="switch">
<input class="switchInput" role="switch" type="checkbox" value="3" name="analytics2">
<div class="switchToggle">
<span class="switchToggleValue switchToggleValue--on">yes</span>
<span class="switchToggleValue switchToggleValue--off">no</span>
</div>
</div>
<br>
<div class="switch">
<input class="switchInput" role="switch" type="checkbox" value="3" name="analytics2">
<div class="switchToggle">
<span class="switchToggleValue switchToggleValue--on">no</span>
<span class="switchToggleValue switchToggleValue--off">yes</span>
</div>
</div>
<br>
<div class="switch">
<input class="switchInput" role="switch" type="checkbox" value="3" name="analytics2">
<div class="switchToggle">
<span class="switchToggleValue switchToggleValue--on">diakh</span>
<span class="switchToggleValue switchToggleValue--off">ara</span>
</div>
</div>
<br>
<div class="switch">
<input class="switchInput" role="switch" type="checkbox" value="3" name="analytics2">
<div class="switchToggle">
<span class="switchToggleValue switchToggleValue--on">ara</span>
<span class="switchToggleValue switchToggleValue--off">diakh</span>
</div>
</div>