我正在尝试使用CSS网格来布局2列HTML表单。
在第一列中,我放置标签,每行一个。在第二列中,我放置表单元素,每行一个。
这是我的第一个问题,我对CSS和HTML都是陌生的。有人可以指出我所误解的方向吗?这将不胜感激。谢谢。
这是CSS,然后是HTML,我已填写表格。
@media screen and (min-width: 600px) {
form {justify-self: start;
max-width: 600px;
display: grid;
grid-template-columns: 20% 1fr%;
grid-template-rows: repeat(6, 20%);
grid-gap: 20px;
font-family: Arial, Helvetica, sans-serif;
}
label[for="menu"] {
grid-area: 1 / 1 / 1 / 2;
}
label[for="bio"] {
grid-area: 2 / 1 / 2 / 2;
}
label[for="name"]{
grid-area: 3 / 1 / 3 / 2;
}
label [for="email"]{
grid-area: 4 / 1 / 4 / 2;
}
.grid5 {
grid-area: 5 / 1 / 5 / 2;
}
.grid6 {
grid-area: 6 / 1 / 6 / 2;
}
select {
grid-area: 1 / 2 / 1 / 3;
}
textarea {
grid-area: 2 / 2 / 2 / 3;
}
#name {
grid-area: 3 / 2 / 3 / 3;
}
#email {
grid-area: 4 / 2 / 4 / 3;
}
}
<div class="form">
<form action="" method="post">
<div id="grid1"> <label for="menu">Type</label> <select name="pet_name" id="menu">
<option>Cat</option>
<option>Dog</option>
<option>Hamster</option>
<option>Zebra</option>
<option>Other</option>
</select>
</div>
<div id="grid2"> <label for="bio">Biography</label> <textarea name="pet_bio" id="bio"></textarea> </div>
<div id="grid3"> <label for="name">Name</label> <input type="text" id="name" name="pet_name"> </div>
<div id="grid4"> <label for="email">Owners Email</label> <input id="email" name="pet_owner_email"></div>
<div id="grid5"> <button type="submit" id="new-pet-submit-button">Create New Pet</button> </div>
<div id="grid6"> <button type="reset" id="reset">Reset</button></div>
</form>
</div>
CSS网格仅影响第一级的所有对象。
消除表单元素周围的div使CSS代码起作用。
例如:
@media screen and (min-width: 600px) {
form {justify-self: start;
max-width: 600px;
display: grid;
grid-template-columns: 20% 1fr%;
grid-template-rows: repeat(6, 20%);
grid-gap: 20px;
font-family: Arial, Helvetica, sans-serif;
}
label[for="menu"] {
grid-area: 1 / 1 / 1 / 2;
}
label[for="bio"] {
grid-area: 2 / 1 / 2 / 2;
}
label[for="name"]{
grid-area: 3 / 1 / 3 / 2;
}
label [for="email"]{
grid-area: 4 / 1 / 4 / 2;
}
.grid5 {
grid-area: 5 / 1 / 5 / 2;
}
.grid6 {
grid-area: 6 / 1 / 6 / 2;
}
select {
grid-area: 1 / 2 / 1 / 3;
}
textarea {
grid-area: 2 / 2 / 2 / 3;
}
#name {
grid-area: 3 / 2 / 3 / 3;
}
#email {
grid-area: 4 / 2 / 4 / 3;
}
}
<div class="form">
<form action="/pets" method="post">
<label for="menu">Type</label> <select name="pet_name" id="menu">
<option>Cat</option>
<option>Dog</option>
<option>Hamster</option>
<option>Zebra</option>
<option>Other</option>
</select>
<label for="bio">Biography</label> <textarea name="pet_bio" id="bio"></textarea>
<label for="name">Name</label> <input type="text" id="name" name="pet_name">
<label for="email">Owners Email</label> <input id="email" name="pet_owner_email">
<button type="submit" id="new-pet-submit-button">Create New Pet</button>
<button type="reset" id="reset">Reset</button>
</form>
</div>