Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space on left and right in a 100% width flex container with horizontal scroll

Tags:

html

css

flexbox

I have a flex container that is 100% width with a horizontal scroll. I want to have space on left and right in the scroll, but margin-right of the divs doesn't create space on the right side, also I have another container wrapping the container to hide the scrollBar with padding-bottom.

I know that I can use white-space: nowrap in a block container in which margin-right works, but I want to use flex-box. Also I am setting the divs' width with min-width:

Also I know that in this case min-width: 22% = 22vw, but I want to do it with percantage. jsfiddle code open

body{
  width: 100%;
  height: 10vh;
  margin: 0;
}
div{
    height: 100%;
}
.container{
  width: 100%;
}
.container > div{
  overflow-y: hidden;
  display: flex;
  width: 100%;
}
.container > div > div{
  min-width: 20%;
  display: inline-block;
  margin: 0 5px;
  background: red;
}
like image 620
ivaylo Avatar asked Oct 27 '25 14:10

ivaylo


2 Answers

Here is little trick about the margin-right which wasn't applied on the last div you can easily add another div and make it small as possible for example like 0.1px but if it is 0px it won't work this will make the last div left space between them but the last div will not be visible so it will sound like its margin has been applied

body {
  width: 100%;
  height: 40vh;
  margin: 0;
}

div {
  height: 100%;
}

.container {
  width: 100%;
}

.container>div {
  /*overflow-y: hidden;*/
  overflow-x: scroll;
  display: flex;
  width: 100%;
}

.container>div>div {
  min-width: 20%;
  display: inline-block;
  margin: 0 10px;
  background: red;
}

.container>div>div:last-child {
  min-width: 0.1px;
  height: 100%;
}
<div class="container">
  <div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>
like image 62
Umutambyi Gad Avatar answered Oct 30 '25 05:10

Umutambyi Gad


So, I think the issue is your min-width setting. 20% of 100 would only allow 5 blocks without spacing. 7 blocks would need to be ~14% + spacing to allow enough room. So you can take out the min-width, convert your margin spacing to something proportional and add flex:1 to .container > div > div. jsfiddle

like image 22
Mister Pea Avatar answered Oct 30 '25 07:10

Mister Pea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!