在网格中如何将元素垂直移至末尾?

huangapple go评论60阅读模式
英文:

How to move element to the end vertically in grid?

问题

body {
  display: grid;
  height: 500px;
  align-content: start;
  justify-content: center;
  background: gray;
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

div:nth-of-type(3) {
  align-self: end;
  background: blue;
}
英文:

I need two divs to be at the top of body and one div (blue one) at the bottom of body. All of them must be centered horizontally. I need to do it using grid. What am I doing wrong? Please help.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

body {
  display: grid;
  height: 500px;
  align-content: start;
  justify-content: center;
  background: gray;
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

div:nth-of-type(3) {
  align-self: end;
  background: blue;
}

<!-- language: lang-html -->

&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

使用 grid-template-rows,并使用 1fr 使最后一列占据剩余的空间。

body {
  margin: 0;
  display: grid;
  height: 100vh; /* full heught screen */
  grid-template-rows: auto auto 1fr;
  justify-content: center;
  background: gray;
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

div:nth-of-type(3) {
  align-self: end;
  background: blue;
}
<div></div>
<div></div>
<div></div>
英文:

Use grid-template-rows and make the last column take the remaining space using 1fr

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

body {
  margin: 0;
  display: grid;
  height: 100vh; /* full heught screen */
  grid-template-rows: auto auto 1fr;
  justify-content: center;
  background: gray;
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

div:nth-of-type(3) {
  align-self: end;
  background: blue;
}

<!-- language: lang-html -->

&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月31日 02:08:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定