我有一个具有设定宽度的容器,因此它的子项会溢出并强制您滚动。每个子元素 ( .box
) 都有一个 margin-right: 10px
。边距一直显示,直到到达最后一个元素,此时它在元素的最右边缘(不包括边距)被切断。我希望它显示最后一个元素的边距,但我无法弄清楚如何在不添加不必要的 div 来使间距正常工作的情况下完成这项工作,这似乎是一个困惑的解决方案。
橙色区域应包含在容器内(红色轮廓)
此处可编辑代码笔:https://codepen.io/starkana/pen/wvMjdjY
.container {
display: flex;
flex-flow: row nowrap;
border: 1px solid red;
width: 170px;
overflow: scroll;
padding: 0px;
}
.box {
background: gray;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
display: flex;
margin-right: 10px !important;
flex-shrink: 0;
}
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
最佳答案
想法#1
在查看您的问题时,我想到的最简单的事情是创建另一个 div 来包含“可滚动内容”。这样,滚动部分周围总是有空间,这样看起来就好像没有被切断。
我在这里创建了一个 JSFiddle,Idea #1
代码
.container {
display: flex;
flex-flow: row nowrap;
border: 1px solid red;
width: 170px;
overflow: scroll;
padding: 5px;
}
.scrollSection {
display: flex;
flex-flow: row nowrap;
width: 170px;
overflow: scroll;
padding: 1px;
}
.box {
background: gray;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
display: flex;
margin-right: 10px !important;
flex-shrink: 0;
/* padding-right: 10px !important; */
}
<div class="container">
<div class="scrollSection">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
</div>
想法#2
我有另一种解决这个问题的方法,我遇到了这个JSFiddle
我制作了这个想法的一个版本,以便它可以在您的用例场景中工作:
.container {
display: flex;
flex-flow: row nowrap;
border: 1px solid red;
width: 170px;
overflow: scroll;
padding: 5px;
}
.scrollSection {
display: flex;
flex-flow: row nowrap;
width: 170px;
overflow: scroll;
padding: 1px;
}
.margin-end {
background: blue;
width: 10px;
height: 40px;
align-items: center;
justify-content: center;
display: flex;
margin-right: 0px;
flex-shrink: 0;
margin-left: -10px;
}
.box {
background: gray;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
display: flex;
margin-right: 10px !important;
flex-shrink: 0;
/* padding-right: 10px !important; */
}
.container:nth-last-child(2) {
margin-right: 0px !important;
background: blue !important;
}
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="margin-end">
</div>
</div>
我还为此创建了一个 JSFiddle,Idea #2
关于html - 如何在具有溢出滚动的父元素中包含子元素的边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62819377/