Home > OS >  Move all except one item to a single row with scrollbar in flexbox
Move all except one item to a single row with scrollbar in flexbox

Time:10-30

I have some layout like this:

.foo {
  display: flex;
  flex-wrap: wrap;
}

.bar {
  padding: 1rem 6rem;
  text-align: center;
  background: #A0E7E5;
}

.active {
  background: #B4F8C8;
  order: 99;
  width: 100%;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
</div>

Is there a way to prevent wrapping of the blue divs and instead show a scrollbar for the first row (preferably without layout modification)? Basically any of the items (.bar) can be marked as .active and I want to show the active one on a separate row at end.

CodePudding user response:

You can use CSS Grid to achieve a similar effect. Make foo a grid with 2 rows and give it some width. Then add overflow property to it to create scrollbar. By default place all bar div on the first row and all the .bar.active to the second row.

.foo {
  display: flex;
  flex-wrap: wrap;
}

.bar {
  padding: 1rem 6rem;
  text-align: center;
  background: #A0E7E5;
}

.foo {
  width: 500px;
  overflow-x: auto;
  display: grid;
  grid-template-rows: 1fr 1fr;
}

.bar {
  grid-row: 1;
}

.active {
  grid-row: 2;
  background: #B4F8C8;
  width: 100%;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div >
    <div >1</div>
    <div >2</div>
    <div >3</div>
    <div >4</div>
    <div >5</div>
  </div>
</body>

</html>

CodePudding user response:

.bar {
  padding: 1rem 6rem;
  text-align: center;
  background: #a0e7e5;
  flex: auto;
}

You can add flex:auto on to the bar class which kinda solves the problem and there will be no need of scrollbar.

  •  Tags:  
  • css
  • Related