I started studying the CSS grid and I’m trying to build a form. I can’t wrap my head around why the and are being rendered on a different row. I want them both in the same area. And I don’t want to work with implicit labeling. (As I want to render the radiobutting left of its label.)
Is it possible to render them both in one area (or ‘cell’ if you like)?If not, the only solution is to create a seperate grid with three columns?
A second question: I’ve read allready that the doesn’t work well with grid. To solve this, I’ve put a in it. But for some reason, the can’t be part of the . (While these radiobuttons do, semanticwise, belong to this section. What seems to be the problem?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Verzoekschrift 284</title>
<link href="https://necolas.github.io/normalize.css/latest/normalize.css" rel="stylesheet" type="text/css">
<style>
form {
padding: 1em;
}
section {
display: contents;
}
fieldset {
padding: 0;
margin: 0;
border: none;
}
.twoColumns {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-areas:
"leftColumn rightColumn";
gap: 1em;
padding-bottom: 1em;
justify-items: start;
}
.twoColumns > label {
grid-column: leftColumn;
}
.twoColumns > input {
grid-column: rightColumn;
}
.twoColumns-right > label,
.twoColumns-right > input {
grid-column: rightColumn;
}
</style>
</head>
<body>
<form id="myForm">
<section class="twoColumns" title="Title1">
<h1>Title h1</h1>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="surname">surname:</label>
<input type="text" id="surname" name="surname">
</section>
<fieldset>
<div class="twoColumns twoColumns-right">
<legend>Gender:</legend>
<input type="radio" id="man" name="gender" value="man">
<label for="man">Man</label>
<input type="radio" id="woman" name="gender" value="woman">
<label for="vrouw">Woman</label>
</div>
</fieldset>
</form>
</body>
</html>
I tried a new three-column-grid. This works, but creates a new problem: the two-grid an three-grid aren’t lining up layoutwise.
Tried applying display: inline-block on both label and input, this doesn’t work.
Played around with display: contents. No (positive) result.
2
Answers
just changed your code little bit. remove unnecessary CSS also add some div like gender-input to separate gender input and label and use flex to change their layout so they can be in same row.
final code
The Grids layout works by positioning each child element in individual grid cells. It is also worth noting that bare text will be treated as an individual grid cell as well.
Therefore, as you have
label
andinput
as direct child elements of the grid container, they are in separate grid cells. In order to treat thelabel
andinput
as one unit to be positioned in the same cell, you’ll need to wrap them inside of another element, such asdiv
.Also, realize that the
legend
element is permitted only to be the first child of afieldset
. Therefore, it is invalid for you to putlegend
as the first child of adiv
.