Kevin Suttle Kevin Suttle - 6 months ago 28
CSS Question

Flexbox: 2 column grid with empty first column

Is it possible to align a 2 column grid, where the items on the 2nd row align with the 2nd column? This is super hard to explain verbally, so I drew up what I'm aiming for.
enter image description here

Ideally, there would be no nesting of HTML elements. They're all siblings.
Also, if possible, I'd prefer to not swap CSS classes via JS.

Answer

Turns out there are two possible answers to this that don't invlolve flexbox.

  1. display: table-row
  2. CSS Grids

.tableContainer {
  display: table-row;
  background: red;
}
input {
  background: yellow;
}
label {
  background: aquamarine;
}
.inputLabel {
  display: table-cell;
}
.error {
  font-size: smaller;
  font-style: italic;
  display: table-row;
}

/* */ 

inputLabel_GridItem,
.error_GridItem {
  display: initial;
}

.inputLabel_GridItem {
  grid-area: label;
  padding: 20px;
}

.error_GridItem {
  color: white;
  background-color: red;
  grid-area: error;
  padding: 20px;
}

.gridContainer {
  display: grid;
  grid-template-columns: 100px 300px;
  grid-template-areas: "label input""....... error";
  grid-gap: 10px;
}
<h2> display: table </h2>

<form novalidate class="tableContainer">
  <label for="textField" class="inputLabel">Name</label>
  <input type=text id="textField" placeholder="full name" />
  <label for="textField" class="error">error</label>
</form>

<h2> CSS Grids </h2>
<form novalidate class="gridContainer">
  <label for="textField" class="inputLabel_GridItem">Name</label>
  <input type=text id="textField" placeholder="full name" />
  <label for="textField" class="error_GridItem">error</label>
</form>

Comments