html 如何在css网格单元格中定位元素?

hl0ma9xz  于 2023-01-28  发布在  其他
关注(0)|答案(3)|浏览(149)

CSS网格,三个单元格,每个单元格中有三个元素:标题,段落,链接。2每个段落都有不同的长度,使得链接没有对齐。3有什么方法可以对齐链接,最好是将元素放在单元格的底部?

.grid {
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
}
<div class="grid">
  <div>
    <h3>Item 1</h3>
    <p>Description</p>
    <a href="#">Link 1</a>
  </div>
  <div>
    <h3>Item 2</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
    <a href="#">Link 2</a>
  </div>
  <div>
    <h3>Item 3</h3>
    <p>Description</p>
    <a href="#">Link 3</a>
  </div>
</div>

https://codepen.io/anon/pen/GYEobV

11dmarpk

11dmarpk1#

您可以为最外层的父节点保留grid布局,将内部的div转换为flex容器,最后在flex-end位置自对齐链接元素:

.grid {
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.grid div {
  display: flex;
  flex-direction: column;
  justify-content: stretch;
}
.grid div a {
  margin-top: auto;
  width: 100%
  align-self: flex-end;
}
<div class="grid">
  <div>
    <h3>Item 1</h3>
    <p>Description</p>
    <a href="#">Link 1</a>
  </div>
  <div>
    <h3>Item 2</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
    <a href="#">Link 2</a>
  </div>
  <div>
    <h3>Item 3</h3>
    <p>Description</p>
    <a href="#">Link 3</a>
  </div>
</div>
bjp0bcyl

bjp0bcyl2#

使用position:absolute;你可以解决你的问题检查更新的代码段

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

.col {
  position: relative;
}

a {
  position: absolute;
  bottom: 0;
}
<div class="grid">
  <div class="col">
    <h3>Item 1</h3>
    <p>Description</p>
    <a href="#">Link 1</a>
  </div>
  <div class="col">
    <h3>Item 2</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
    <a href="#">Link 2</a>
  </div>
  <div class="col">
    <h3>Item 3</h3>
    <p>Description</p>
    <a href="#">Link 3</a>
  </div>
</div>
w6mmgewl

w6mmgewl3#

在给出最初的答案之后,这可能已经发生了变化,但是目前well-supportedjustify-itemsalign-items属性是对齐网格单元格中的项目的一种方便的方法,这也是最初的问题所要求的。
例如,下面的代码将根据请求将网格单元格的内容与单元格的底部对齐:

.grid {
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
  align-items: flex-end;
}

相关问题