右侧对齐网格元素的方法
P粉296080076
P粉296080076 2023-08-13 11:27:01
[CSS3讨论组]

我在CSS Grid布局中有固定数量的列,并且有要放置在这些列中的元素。要放置的元素数量小于列的数量。

我希望这些列向右对齐,按照元素添加的顺序。在下面的代码中,有4个元素向左对齐,其右侧有6个空元素:


.hello {
  border-style: solid;
  border-color: blue;
}

.container {
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(10, 5rem);
}
<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
  <div class="hello">4</div>
</div>


我想要将上面的布局更改为:

empty  empty  empty  empty  empty  empty   1    2    3    4

我尝试了各种组合的[align,justify]-[content,items],但都没有达到向右对齐的效果。CSS Grid能实现这个吗?

P粉296080076
P粉296080076

全部回复(1)
P粉208469050

由于数量有限,您可以手动定义它们

.hello {
  border-style: solid;
  border-color: blue;
}

.container {
  display: grid;
  gap: 5px;
  grid-template-columns: repeat(10, 3rem);
  margin: 5px;
}

.container > :nth-last-child(1) {grid-column-end: -1}
.container > :nth-last-child(2) {grid-column-end: -2}
.container > :nth-last-child(3) {grid-column-end: -3}
.container > :nth-last-child(4) {grid-column-end: -4}
.container > :nth-last-child(5) {grid-column-end: -5}
.container > :nth-last-child(6) {grid-column-end: -6}
.container > :nth-last-child(7) {grid-column-end: -7}
.container > :nth-last-child(8) {grid-column-end: -8}
.container > :nth-last-child(9) {grid-column-end: -9}
<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
  <div class="hello">4</div>
</div>

<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
</div>

<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
  <div class="hello">4</div>
  <div class="hello">5</div>
  <div class="hello">6</div>
</div>

但最好使用flexbox:

.hello {
  border-style: solid;
  border-color: blue;
  width: 3rem;
}

.container {
  display: flex;
  gap: 5px;
  width: calc(10*3rem + 9*5px);
  margin: 5px;
}

.container > :first-child {margin-left:auto}
<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
  <div class="hello">4</div>
</div>

<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
</div>

<div class="container">
  <div class="hello">1</div>
  <div class="hello">2</div>
  <div class="hello">3</div>
  <div class="hello">4</div>
  <div class="hello">5</div>
  <div class="hello">6</div>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号