CSS 大于屏幕宽度

问题描述 投票:0回答:2

我有一个比视口宽的 CSS 网格。我希望能够向右滚动以显示网格的其余部分,但由于某种原因,网格的背景颜色只是视口的大小,所以当我开始向右滚动时,没有背景。

.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>

html css css-grid
2个回答
1
投票

发生这种情况是因为当前 div“表格”溢出视口,因为背景颜色仅限于此 div 而不是您无法看到的视口。你需要给这个 div 一个固定的宽度/最大宽度并设置

overflow-x: auto;
来达到你想要的结果,这限制了 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>


0
投票

这可能是因为重复 (6,50%) 把事情搞砸了。如果将其更改为 50vw(视口的 50%)或 1fr 并将网格设置为内联网格,这将按预期工作:

.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>

© www.soinside.com 2019 - 2024. All rights reserved.