如何实现单选按钮文本换行后的悬挂缩进效果
实现单选按钮文本的悬挂缩进效果
要实现你要的单选按钮文本换行后悬挂缩进效果,原来的text-indent方案不适用——因为单选按钮和文本是 inline 排列的,没法让换行后的文本对齐到第一行开头。试试下面的布局调整和样式修改:
核心思路
- 将
label设为块级元素并添加左侧内边距,给单选按钮预留位置 - 把自定义单选按钮绝对定位到
label的左侧内边距区域,不占用文本布局空间 - 文本自然填充
label的内边距范围,换行后自动形成悬挂缩进
修改后的代码
CSS 样式
.sideBar { width: 100px; padding: 10px; font-size: 1em; font-weight: 100; } label { display: block; /* 每个选项独占一行,替代<br>标签 */ line-height: 1.5; position: relative; /* 作为内部绝对定位元素的容器 */ padding-left: 1.2em; /* 为单选按钮留出足够空间 */ margin-bottom: 0.5em; /* 可选,增加选项之间的间距 */ } .custom-radio { appearance: none; -webkit-appearance: none; -moz-appearance: none; width: 0.8em; height: 0.8em; border-radius: 50%; border: 1px solid #FFA500; position: absolute; /* 脱离文本流,定位到label左侧 */ left: 0; top: 0.35em; /* 垂直居中对齐文本 */ } .custom-radio:checked { background-color: #FFA500; border-color: #FFA500; } .indented { /* 无需原来的text-indent,删除即可 */ }
HTML 结构
<div class="sideBar"> <label> <input type="radio" class="custom-radio" name="locations" value=1 /> <span class="indented">Location 1</span> </label> <label> <input type="radio" class="custom-radio" name="locations" value=2 /> <span class="indented">Location xxx xxx xxx</span> </label> </div>
效果说明
修改后,文本换行时会自动对齐到第一行文本的开头位置,形成你想要的悬挂缩进:
o Location 1
o Location xxx
xxx xxx
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

