右側對齊網格元素的方法
P粉296080076
P粉296080076 2023-08-13 11:27:01
0
1
565
<p>我在CSS Grid佈局中有固定數量的列,並且有要放置在這些列中的元素。要放置的元素數量小於列的數量。 </p> <p>我希望這些列向右對齊,按照元素添加的順序。在下面的程式碼中,有4個元素向左對齊,其右側有6個空元素:</p> <p><br /></p> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hello { border-style: solid; border-color: blue; } .container { display: grid; grid-gap: 5px; grid-template-columns: repeat(10, 5rem); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"> <div class="hello">1</div> <div class="hello">2</div> <div class="hello">3</div> <div class="hello">4</div> </div></code></pre> <p><br /></p> <p>我想要將上面的佈局更改為:</p> <pre class="brush:php;toolbar:false;">empty empty empty empty empty empty 1 2 3 4</pre> <p>我嘗試了各種組合的<code>[align,justify]-[content,items]</code>,但都沒有達到向右對齊的效果。 CSS Grid能實現這個嗎? </p>
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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!