1

I have a very specific UX request. I have four links within a container, one next to each other in one row, separated by a vertical line.

Example:

Link one | Link two | Link three | Link four

This is the layout if they all fit within the container. Once the user decrease the screen size and the links don't fit anymore, I want to switch the layout to 2 rows and 2 columns. And to have a horizontal divider between the rows. Also, the existence of links is variable. If there are just three links, the third link is extended over the whole bottom row.

Example:

Link one | Link two


Link three | Link four

Or

Link one | Link two


Link three

I would like to achieve this behaviour without using JS if possible. Ideally by using Flexbox or Bootstrap. Is it possible?

Jan Horčička
  • 671
  • 1
  • 11
  • 26
  • I think that what you are looking for is `flex: wrap;` https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap – ATP Aug 29 '21 at 20:37
  • Unless I'm mistaken, this will wrap just one element that is overflowing. I want to immediately jump to two rows & two columns layout. – Jan Horčička Aug 29 '21 at 20:48
  • Does this answer your question? [Arrange 2 items per row using flexbox](https://stackoverflow.com/questions/45037844/arrange-2-items-per-row-using-flexbox) – ATP Aug 29 '21 at 20:52

1 Answers1

1

You can try with grid and media query:

.container {
   display: grid;
   grid-template-columns: repeat(4, 1fr);
   text-align: center;
   margin: 1em;
}
a {
  border-right: 1px solid grey;
}
a:last-child {
   border-right: none;
}
@media screen and (max-width: 500px) {
 .container {
    grid-template-columns: repeat(2, 1fr);
  }
  .container a:nth-child(1), a:nth-child(2) {
    border-bottom: 1px solid grey;
  }
  a:nth-child(2) {
    border-right: none;
  }
  a:nth-child(3):last-child {
    grid-column: 1/3;
  }
}
<div class="container">
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
  <a>Link 4</a>
</div>

<div class="container">
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
</div>
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
  • That's brilliant. Is there also a way to make the "Link 3" be across the whole bottom row in case there are only 3 links? So it will be 6, 6, 12. – Jan Horčička Aug 29 '21 at 21:20
  • Sorry mate, i don't know is it possible to do that without JS. If we know that there will be 3 links then we need only to set `grid-column: 1/3` on third link. But we don't know number of links :( – Nikola Pavicevic Aug 29 '21 at 21:27
  • Is it possible to use the number of siblings as described here? https://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has – Jan Horčička Aug 29 '21 at 21:35
  • Thanks a lot mate, i learned something new tonight :) Answer is corrected, take a look pls :) – Nikola Pavicevic Aug 29 '21 at 21:59