如何将页面单选按钮(Radio Buttons)与对应文本左对齐
解决单选按钮与问题文本对齐的方案
要实现单选按钮与对应问题的首字符对齐(且对齐最长问题的首字符),可以通过调整HTML结构和CSS样式来实现,具体步骤如下:
1. 优化HTML结构
梳理问题与选项的层级结构,让布局更清晰可控:
<!doctype html> <html lang="en"> <head> <title>Simulatore Quiz AREU</title> </head> <body> <form action='/risultati' method='POST'> <ol class="quiz-list"> {% for i in q %} <li class="quiz-item"> <div class="question-text">{{ i }}</div> <div class="options-group"> {% for j in o[i] %} <label class="option-label"> <input type='radio' value='{{ j }}' name='{{ i }}' required/> {{ j }} </label> {%- endfor %} </div> </li> {%- endfor %} </ol> <button type="submit" name="submit_button"> Finisci Test</button> </form> </body> </html>
2. 修改CSS样式
重点调整布局对齐规则,移除干扰样式并添加对齐逻辑:
/* https://www.bootdey.com/snippets/view/microsoft-metro-tiles-bootstrap#html */ .site-title { margin-top: 2rem; margin-bottom: 3.5rem; font-weight: 500; line-height: 1.2; color: black; text-align: center; } body { min-height: 100vh; display: flex; flex-direction: column; align-items: center; /* 让form整体居中,而非全局文本居中 */ } form { margin: 10px; width: 1200px; text-align: left; /* 问题和选项左对齐 */ } /* 核心对齐样式 */ .quiz-list { list-style-position: inside; /* 列表标记与文本同框 */ padding-left: 0; margin: 0; } .quiz-item { margin-bottom: 1.5rem; /* 问题之间的间距 */ } .options-group { margin-top: 0.5rem; } .option-label { display: block; text-indent: -1em; /* 文本向左偏移1em */ padding-left: 1em; /* 给单选按钮留出位置 */ margin-bottom: 0.3rem; align-items: center; } input[type="radio"] { margin-right: 5px; } form button[type="submit"] { margin-top: 30px; position: relative; overflow: hidden; background-color: #d00000; color: white; border: 0; padding: 1.5em 0.7em; } footer { margin-top: auto; text-align: center; } p, span, a, ul, li, button { font-family: inherit; font-size: inherit; font-weight: inherit; line-height: inherit; } strong { font-weight: 600; } h1, h2, h3, h4, h5 { font-family: 'Open Sans', "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serify, serif; line-height: 1.5em; font-weight: 300; } .card-tile { width: 100%; display: inline-block; box-sizing: border-box; background: #fff; padding: 20px; margin-bottom: 30px; } .card-title { margin-top: 0; text-align: center; } .purple, .blue, .red, .orange, .green { color: #fff; } .red { background: #d00000; }
关键说明
- 移除
form的display: contents属性,避免form失去容器特性导致布局失控 - 将
body的text-align: center改为align-items: center,仅让form整体居中,内部文本左对齐 - 通过
text-indent: -1em与padding-left: 1em的组合,让单选按钮刚好对齐问题文本的首字符位置 - 统一问题与选项的间距,提升布局整洁度
内容的提问来源于stack exchange,提问作者lucians
相关产品推荐
相关产品推荐

