Adding a dividing line across all columns in CSS Grid

主宰稳场 提交于 2019-12-11 06:05:52

问题


In my grid, I display my items in 3 columns.

I want to draw a red divider between the 3 columns.

I tried to add a right border to the cells.

The problem: When the number of items is 4 (or 7 or 10 and so on) the right border of the 5th cell in the grid is missing, since there is no item in this grid cell. I want the border between the 2nd and 3rd column to reach till the bottom of the grid.

In different screen resolutions the number of columns may be different (2 or 4).

I want to handle this using CSS only (with media query). I don't want any HTML or JS involved.

ul {
   display: grid;
   grid-template-columns: 33% 33% 33%;
   grid-column-gap: 10px;
   width: 500px;
   border: 1px solid black;
   padding: 5px;
   list-style: none;
}
    
li {
   border-right: 2px solid red;
}
    
li:nth-child(3n) {
   border-right: none;
}
<ul>
  <li> A </li>
  <li> B </li>
  <li> C </li>
  <li> D </li>
</ul>

https://jsfiddle.net/rh5ru19r/6/

Is there another way to draw a divider between the columns?

Thanks for your help.


回答1:


Since you're open to using media queries, and the number of columns is known (2, 3 or 4), you may be able to use the background color of the grid and pseudo-elements to make your layout work.

revised jsfiddle demo

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(21%, 1fr));
  grid-column-gap: 2px;
  background-color: red;
  border: 1px solid black;    
  padding: 0;
  margin: 0;
  list-style: none;
}

@media ( max-width: 700px ) {
  ul { grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); }
  ul::before { content: ""; background-color: white; order: 1; }
  ul::after  { content: ""; background-color: white; order: 2; }  
}

@media ( max-width: 400px ) {
  ul { grid-template-columns: repeat(auto-fill, minmax(40%, 1fr)); }
  ul::before { content: none; }
  ul::after  { content: none; }  
}

li {
  padding: 5px;
  text-align: center;
  background-color: white;
}
<ul>
  <li> A </li>
  <li> B </li>
  <li> C </li>
  <li> D </li>
</ul>


来源:https://stackoverflow.com/questions/49257920/adding-a-dividing-line-across-all-columns-in-css-grid

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