具有 CSS 属性的解决方案
在下面的示例中,我们使用三个 <div> 元素并将 <label> 和 <input> 元素放置在每个元素中。
请注意,我们为每个 <input> 使用了一个 type 属性。
我们指定 <div> 元素的边距底部。
然后,我们将 <label> 元素的显示设置为“inline-block”并给出固定宽度。
之后,将 text-align 属性设置为“right”,标签将与右侧的输入对齐。
带有 text-align 属性的输入旁边的右对齐标签示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
div {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 150px;
text-align: right;
}
</style>
</head>
<body>
<form action="/form/submit" method="post">
<div>
<label>Short</label>
<input type="text" />
</div>
<div>
<label>Simple label</label>
<input type="text" />
</div>
<div>
<label>Label having more text</label>
<input type="text" />
</div>
</form>
</body>
</html>
我们可以移除 text-align 属性,默认情况下标签将左对齐。
让我们看一个例子,我们还在输入和标签上的属性上添加占位符、id 和 name 属性。
因此,单击标签时将激活输入。
输入旁边的左对齐标签示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
div {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 150px;
}
</style>
</head>
<body>
<form action="/form/submit" method="post">
<div>
<label for="name">Name</label>
<input type="text" id="name" placeholder="Enter your name" />
</div>
<div>
<label for="age">Your Age</label>
<input type="text" id="age" name="age" placeholder="Enter your age" />
</div>
<div>
<label for="country">Enter Your Country</label>
<input type="text" id="country" name="country" placeholder="Country" />
</div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
在我们的下一个例子中,我们也会左对齐标签。
其中我们还制作了 <label> 内联块并给出了一个固定的宽度。
对于 <input> 元素,我们添加了填充。
输入旁边的左对齐标签示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
div {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 110px;
color: #777777;
}
input {
padding: 5px 10px;
}
</style>
</head>
<body>
<form action="/form/submit" method="post">
<div>
<label for="name">Your name:</label>
<input id="name" name="username" type="text" autofocus />
</div>
<div>
<label for="lastname">Your Last name:</label>
<input id="lastname" name="lastname" type="text" />
</div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
创建 Web 表单时,我们可能需要知道如何将标签与输入对齐。
其中我们将展示如何在输入旁边创建右对齐和左对齐的 <label> 元素。
日期:2020-06-02 22:15:05 来源:oir作者:oir
