CSS Grid Horizontal scroll, adding space before and after scrolled items

喜夏-厌秋 提交于 2019-12-10 10:06:40

问题


I am using CSS grid to create a horizontal scroll for a list of card items. I am required to leave spacing at the first item of the list on the left, and the last item on the list on the right, when you have reached the end of the horizontal scroll. When scrolling through the middle of the list however, there should not be any spacing on the sides.

Requirements

  1. Spacing on the start of the list of cards (on the left)
  2. Spacing at the end of the list of cards (on the right)
  3. The amount of cards shown must be 2.5 (on page load, show 2.5 cards to indicate that scrolling horizontally is availabale)
  4. The number of items in the list can vary, so unable to use an explicit grid

Example of how it should look at the beginning of the list, with spacing on the left side:

Example of how it's supposed to look when scrolling on the right, and what it is not supposed to look like on the left side:

Example of how it's supposed to look like at the end of the list, with spacing on the rightside:

Here is a codepen on what I am trying to achieve.

I have tried using a ::before and ::after on the ol to try and fill in the empty space of the beginning and the end of the list, but it was met with weird results.

   ol {
  padding: 0;
  list-style: none;
  display: grid; 
  grid-auto-flow: column;
  grid-gap: 1rem;
  overflow-x: auto;
  grid-template-columns: 1rem repeat(auto-fill, calc((20rem - 2rem) / var(--visible-cards))) 1rem;
  margin-left: -1rem;
  margin-right: -1rem;

  &::before,
  &::after {
    content: '';
  }

  &::before {
    grid-column: 1;
    background: blue;
  }

  &::after {
    grid-column: -1;
    background: red;
  }

The ::after is not at the end of the list as I thought it would be by applying the grid-column: -1, but instead it is at the end of the visible area, before the horizontal scrolling begins. Does anyone know of a way to achieve the requirements? Thanks in advance if you do!!!


回答1:


If anyone is interested in solving this, in the end I only used a ::after element to act as the space after all the li elements. You can see the updated codepen here: https://codepen.io/sammiepls/pen/qKwxBg




回答2:


Have you tried playing with the element:first-child to add a left margin and the element:last-child to add right margin?

As you are using OL-LI the code would be:

li:first-child {
  margin-left: 10px;
}
li:last-child {
  margin-right: 10px;
}


来源:https://stackoverflow.com/questions/51165983/css-grid-horizontal-scroll-adding-space-before-and-after-scrolled-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!