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

问题描述 投票:0回答:1

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列中对齐标题项?

html5 css3 css-grid
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.