如何在CSS网格的单元格中对齐元素?

时间:2019-04-07 20:52:42

标签: html5 css3 css-grid

body {
  margin: 0 auto;
  max-width: 60%;
}

textarea, input, select {
  width: 100%; /* extend the width of the grid item */
  box-sizing: border-box; /* including padding / border in width */
}

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 30px;
  grid-template-rows: auto auto; /* changed */
  border: solid 1px #000000;
  grid-gap: 10px; /* grid gap to handle spaces between items if needed */
  padding: 5px; /* space between wrapper and grid items */
}

.column1 {
  grid-column: 1/2;
}

.column2 {
  grid-column: 2/3;
}

.column3 {
  grid-column: 3/4;
}

.column4 {
  grid-column: 4/5;
}

.colspan2 {
  grid-column: 2/4;
  grid-row: 2;
}
<div class="wrapper">
<div class="column2">
   header 1
  </div>
  <div class="column3">
   header 2
  </div>
</div>
<div class="wrapper">
  <div class="column1">
    <select>
      <option>een</option>
      <option>twee</option>
    </select>
  </div>
  <div class="column2">
    <input type="text" value="col2" />
  </div>
  <div class="column3">
    <input type="text" value="col3" />
  </div>
  <div class="column4">(i)</div>
  <div class="colspan2">
    <textarea>Hello comments here</textarea>
  </div>
</div>

我有一个CSS网格布局,想将标题元素仅右对齐。我试过-> justify-items:end,但这塞满了整个网格。我如何才能对齐第2列和第3列中的标题项?

1 个答案:

答案 0 :(得分:1)

您可以简单地考虑text-align:right

body {
  margin: 0 auto;
  max-width: 60%;
}

textarea, input, select {
  width: 100%; /* extend the width of the grid item */
  box-sizing: border-box; /* including padding / border in width */
}

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 30px;
  grid-template-rows: auto auto; /* changed */
  border: solid 1px #000000;
  grid-gap: 10px; /* grid gap to handle spaces between items if needed */
  padding: 5px; /* space between wrapper and grid items */
}

.column1 {
  grid-column: 1/2;
}

.column2 {
  grid-column: 2/3;
  text-align:right;
}

.column3 {
  grid-column: 3/4;
  text-align:right;
}

.column4 {
  grid-column: 4/5;
}

.colspan2 {
  grid-column: 2/4;
  grid-row: 2;
}
<div class="wrapper">
<div class="column2">
   header 1
  </div>
  <div class="column3">
   header 2
  </div>
</div>
<div class="wrapper">
  <div class="column1">
    <select>
      <option>een</option>
      <option>twee</option>
    </select>
  </div>
  <div class="column2">
    <input type="text" value="col2" />
  </div>
  <div class="column3">
    <input type="text" value="col3" />
  </div>
  <div class="column4">(i)</div>
  <div class="colspan2">
    <textarea>Hello comments here</textarea>
  </div>
</div>