多切换列表布局疑问:如何实现标签右对齐、开关左对齐
实现开关面板的对齐布局
要实现文本从中心向右对齐、开关从中心向左对齐的效果,只需调整布局方式即可达成,无论标签字符串长度如何,所有开关都能保持统一对齐。
修改后的完整代码
CSS 部分
@import url("https://fonts.googleapis.com/css?family=Roboto"); body { font: normal normal normal 1rem/1 'Roboto'; color: black; } .wrapper { display: table; position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 17.5rem; padding: 0; background: transparent; border-radius: 0; text-align: center; margin: auto; overflow: hidden; z-index: 100; } .wrapper .content { padding: 1.5rem 1.5rem 1rem; } .wrapper .header { display: block; font-size: 1.25rem; text-align: center; color: rgba(0, 0, 0, 0.84); margin: 0; padding: 0; transition: color 0.56s cubic-bezier(0.4, 0, 0.2, 1); } .wrapper ul { display: block; padding: 0; width: 100%; } .wrapper ul li { display: flex; justify-content: center; align-items: center; padding: 1rem 0 0; gap: 1rem; } .wrapper ul li p { text-align: right; flex: 0 1 auto; margin: 0; line-height: 1.5rem; transition: color 0.56s cubic-bezier(0.4, 0, 0.2, 1); } .switch { display: inline-block; position: relative; width: 2.5rem; height: 1rem; border-radius: 0.5rem; background: rgba(0, 0, 0, 0.26); transition: background 0.28s cubic-bezier(0.4, 0, 0.2, 1); vertical-align: middle; cursor: pointer; } .switch::before { content: ''; position: absolute; top: -0.25rem; left: -0.25rem; width: 1.5rem; height: 1.5rem; background: #fafafa; box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.28); border-radius: 50%; transition: left 0.28s cubic-bezier(0.4, 0, 0.2, 1), background 0.28s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.28s cubic-bezier(0.4, 0, 0.2, 1); } .switch:active::before { box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.28), 0 0 0 1.25rem rgba(128, 128, 128, 0.1); } input:checked+.switch { background: rgba(139, 195, 74, 0.5); } input:checked+.switch::before { left: 1.25rem; background: #8bc34a; } input:checked+.switch:active::before { box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.28), 0 0 0 1.25rem rgba(139, 195, 74, 0.2); }
HTML 部分
<div class="wrapper"> <div class="content"> <p class="header">Options</p> <ul> <li> <p>Status</p> <input id="test" type="checkbox" hidden="hidden" /> <label class="switch" for="test"></label> </li> <li> <p>User</p> <input id="test1" type="checkbox" hidden="hidden" /> <label class="switch" for="test1"></label> </li> <li> <p>Department</p> <input id="test2" type="checkbox" hidden="hidden" /> <label class="switch" for="test2"></label> </li> </ul> </div> </div>
核心修改说明
- 将列表项(
li)改为flex布局,通过justify-content: center让内部元素整体居中,align-items: center保证文本与开关垂直对齐。 - 给文本标签(
p)设置text-align: right,让文本向右对齐到中线位置,用gap控制文本与开关的固定间距。 - 移除原文本标签的左右外边距,避免干扰布局对齐。
内容的提问来源于stack exchange,提问作者Gangrel
相关产品推荐
相关产品推荐

