How to align elements in cells of a css grid?

好久不见. 提交于 2019-12-10 12:13:09

问题


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>

I have a css grid layout and want to align my header elements only to the right. I tried -> justify-items : end , but this stuffs up the whole grid. How can I just align the header items in column 2 and 3?


回答1:


You can simply consider 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>


来源:https://stackoverflow.com/questions/55563585/how-to-align-elements-in-cells-of-a-css-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!