我有一個(gè)比視窗更寬的CSS網(wǎng)格。我希望能夠向右滾動(dòng)以顯示網(wǎng)格的其余部分,但由于某種原因,網(wǎng)格的背景顏色只有視口的大小,所以當(dāng)我開始向右滾動(dòng)時(shí),沒有背景。
.table {
background-color: blue;
display: grid;
gap: 4px;
grid-template-columns: repeat(6, 50%);
}
.element {
background-color: lightblue;
word-break: break-all;
white-space: nowrap;
}
<div class="table">
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
</div>
這可能是因?yàn)橹貜?fù)(6.50%)把事情搞砸了。如果將它更改為50vw (50%的視口)或1fr,并將柵格設(shè)置為inline-grid,這將按預(yù)期工作:
.table {
background-color: blue;
display: inline-grid;
gap: 4px;
grid-template-columns: repeat(6, 50vw);
}
.element {
background-color: lightblue;
white-space: nowrap;
}
<div class="table">
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
</div>
這是因?yàn)槟壳癲iv & quot表格& quot溢出了視窗,因?yàn)楸尘吧幌抻谶@個(gè)div,而不是視窗,所以你看不到它。您需要給這個(gè)div一個(gè)固定的寬度/最大寬度,并設(shè)置overflow-x:auto;為了獲得您想要的結(jié)果,這將限制div在視口中溢出。
.table {
background-color: blue;
display: grid;
gap: 4px;
grid-template-columns: repeat(6, 50%);
/* adding a fixed width limits this div to overflow within the viewport */
max-width: 100vw;
overflow-x: auto;
}
.element {
background-color: lightblue;
word-break: break-all;
white-space: nowrap;
}
<div class="table">
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
<div class="element">this is an element of the grid</div>
</div>