添加 CSS
- 将 vertical-align 属性设置为“bottom”,这在浏览器之间是一致的。
- 将 position 属性设置为“relative”以相对于其正常位置放置元素。
label {
display: block;
padding-left: 15px;
text-indent: -15px;
}
input {
width: 15px;
height: 15px;
padding: 0;
margin: 0;
vertical-align: bottom;
position: relative;
top: -1px;
}
现在,让我们看看我们的代码的结果。
对齐复选框及其标签的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
label {
display: block;
padding-left: 15px;
text-indent: -15px;
}
input {
width: 15px;
height: 15px;
padding: 0;
margin: 0;
vertical-align: bottom;
position: relative;
top: -1px;
}
</style>
</head>
<body>
<form>
<div>
<label>
<input type="checkbox" /> Label text
</label>
</div>
</form>
</body>
</html>
在这个例子中,我们不需要 for 属性,因为我们将 <input> 包装在 <label> 标签中。
我们可以根据所需的文本大小调整相对定位、高度、宽度等。
接下来,我们将展示一个使用 for 属性的示例。
使用 for 属性对齐复选框及其标签的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
input[type=checkbox],
input[type=radio] {
vertical-align: middle;
position: relative;
bottom: 1px;
}
input[type=radio] {
bottom: 2px;
}
</style>
</head>
<body>
<form>
<label>
<input type="checkbox" /> Label text
</label>
<br/>
<br/>
<input type="checkbox" id="myChk" />
<label for="myChk">label tag with the for attribute</label>
</form>
</body>
</html>
使用 display 属性与“flex”值对齐复选框及其标签的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
label {
display: flex;
align-items: center;
}
</style>
</head>
<body>
<form>
<div>
<label>
<input type="checkbox" /> Label text
</label>
</div>
</form>
</body>
</html>
复选框是每个上使用的 HTML 表单之一。
如何对齐复选框及其标签?
这是开发人员经常问的问题。
这里的问题是,当使用 vertical-align 属性的“基线”值在 Safari 中正确对齐它们时,它们可以工作,但它们在 Firefox 中不起作用,开发人员通常会浪费很多时间来解决这个问题。
如果我们有这样的困难,我们将逐步展示如何去做。
创建 HTML
- 创建 <form> 和 <div> 元素。
- 将“复选框”输入类型放在 <label> 元素中。
<form>
<div>
<label>
<input type="checkbox" /> Label text
</label>
</div>
</form>
日期:2020-06-02 22:14:56 来源:oir作者:oir
