简体   繁体   中英

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

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;
}

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>

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

Extending @Gad answer: There is option to not add additional div at the end. You can just use pseudo element::after/::before and then add something like this. Important note is fact that then div with after pseudo element needs to be position: relative.

.container>div>div:last-child::after {
  content: " ";
    width: 25px;
    height: 100%;
    position: absolute;
    right: -25px;
}

https://jsfiddle.net/0b4tm5y3/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM