我试图通过仅使用基本定位属性来更好地处理CSS定位。目标是获取HTML5 input
,并将其与label
水平对齐,每行一对,左侧为label
,input
} 在右边。基本上会有两列,一列用于labels
,另一列用于inputs
。
我还希望每列都是左对齐的,这是我目前所处的位置。
使用下面的CSS我可以获得我想要的两列外观,但input
个元素都没有正确对齐。
但是,如果我将input
元素的位置设置为absolut
(认为调整left
属性会使每个元素与左边包含相同的像素长度对齐) ,每个元素都是正确的,但是所有元素都在同一行上。
关于如何使用表格或网格列完成双列/左对齐布局的任何提示?
小提琴:http://jsfiddle.net/fjwy3Lov/
CSS
/*Styles for basic form label and input elements*/
.basicForm{
margin: 10px 0 10px 10px;
}
.basicForm label{
float:left;
clear:left;
margin:inherit;
}
.basicForm input{
position:relative;
left:100px;
float:left;
margin: inherit;
}
HTML
<!DOCTYPE html>
<head>
<title>Form Validation Demo</title>
<link href="form.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>HTML 5 Input Types and Form Validation</h1>
<form class="basicForm">
<label for="UserName">User Name:</label>
<input type="text" id="UserName" required="required">
<label for="Password">Password:</label>
<input type="password" id="Password" required="required" />
<label for="UserEmail">Email:</label>
<input type="email" id="UserEmail">
<label for="PhoneNumber">Phone Number:</label>
<input type="tel" id="PhoneNumber">
<label for="Website">Homepage:</label>
<input type="url" id="Website">
<label for="Quantity">Quantity:</label>
<input type="number" id="Quantity" min="1" max="10" step="1" pattern="/\d/">
<label for="StartDate">Start Date:</label>
<input type="date" id="StartDate" min="2000-01-02" max="2016-01-01">
<label for="FavColor">Favorite Color:</label>
<input type="color" id="FavColor">
<label for="CurrentMonth">Current Month:</label>
<input type="month" id="CurrentMonth">
<label for="CurrentWeek">Current Week:</label>
<input type="week" id="CurrentWeek">
<label for="CurrentTime">Current Time:</label>
<input type="time" id="CurrentTime">
<input type="button" id="submit" value="submit">
</form>
</body>
</html>
答案 0 :(得分:2)
这是因为根据您的CSS,所有input
元素都是相应label
左侧的150px,但宽度不同,因此您的input
未对齐。
您需要使所有标签的宽度相同:
.basicForm label{
float:left;
clear:left;
min-width:150px;
}
.basicForm input{
float:left;
}
您也可以使用min-width
,而不是width
,而不是.input-group {
position: relative;
height:2em;
}
.input-group label {
position: absolute;
top: 0;
left: 0;
}
.input-group input {
position: absolute;
top: 0;
left: 100px;
}
。
如果您坚持使用绝对定位,您可以将每个标签/输入对包装在一个div中,这样您就不需要单独定位每个元素,请查看以下示例:
<div class="input-group">
<label>Label 1</label>
<input type="text">
</div>
<div class="input-group">
<label>longer Label</label>
<input type="text">
</div>
<div class="input-group">
<label>short</label>
<input type="text">
</div>
{{1}}