TL;DR:这里的codepen使项目至少有 30px 的边距-右侧,如果是移动视图则没有边距。不使用我认为的 hacky 媒体查询或 jQuery。并且没有水平滚动
为什么?
我想使用弹性盒
以下问题:
3 项
对于桌面,它们排成一排。对于移动设备,可能有 2 个,也可能有 1 个。每个都有margin-right: 30px;
现在,最后一行(可能有1、2 或 3 行)不能有margin-right
或至少看起来好像没有边距。不允许任何黑客攻击。这必须是一个响应式解决方案。
这是非常标准的恕我直言:
例如桌面:
显示 3 个项目,每个项目的最小边距为 30 像素或更多,具体取决于屏幕尺寸。如果空间较少,则flex-wrap
到下一行
在小手机上:
每行只显示一个项目,但居中而不显示margin-right: 30px
我尝试了什么?
HTML
<div class="row no-gutters my-outer">
<div class="col-12 d-flex justify-content-between flex-wrap">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
CSS
.item{
width: 400px;
height: 400px;
background-color: cornflowerblue;
margin-right: 30px;
margin-top: 30px;
}
.my-outer{
margin-top: -30px;
margin-right: -30px;
xxxxwidth: calc(100% - 30px);
}
父级的负边距
问题是,它创建了一个滚动条
应该有一个标准的解决方案,不是吗?
使用width: calc(100% - 30px);
会产生其他不需要的奇怪问题。
在overflow-x: hidden
父元素上使用时,您会遇到以下问题:overflow-x:hidden 仍然可以滚动
由于内置col-12
规则看起来像这样
.col-12 {
flex: 0 0 100%;
max-width: 100%;
}
它可以防止它超过 100%,这是让边距起作用所必需的。因此,如果要删除它,并且由于col-12
元素是一个 flex行项目,如果没有发生换行,它将需要一个宽度,否则它不会填充其父级中的可用空间。
然后,在添加这样的边距时,最好将其添加在项目的左侧,因为左边距通常不会导致出现滚动,而右边距经常会出现,以及该边距的补偿应该应用于项目父项,而不是最外面的元素。
所以在下面的示例中,我删除了col-12
,添加了一个自定义规则my-inner
,并使用了左边距。
现在,对于移动布局,由于无法检测项目何时换行,因此您需要媒体查询或脚本,而且媒体查询实际上不是黑客,只有一个属性需要更改, justify-content
, 这是最干净的解决方案。
堆栈片段
.item{
width: 300px;
height: 300px;
background-color: cornflowerblue;
margin-left: 30px;
margin-top: 30px;
}
.my-inner {
flex-grow: 1;
margin-left: -30px;
margin-top: -30px;
}
@media (max-width: 647px) {
.my-inner {
justify-content: space-around !important;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row no-gutters my-outer">
<div class="d-flex flex-wrap justify-content-between my-inner">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
不过,我个人的建议是使用space-around
,恕我直言,它可以更好地对齐项目,但项目之间的差距很大,并且使用伪元素之一可以使第三个项目保持左对齐。
堆栈片段 2
.my-inner::after,
.item{
width: 300px;
height: 300px;
background-color: cornflowerblue;
margin-left: 30px;
margin-top: 30px;
}
.my-inner::after {
content: '';
height: 0;
}
.my-inner {
flex-grow: 1;
margin-left: -30px;
margin-top: -30px;
}
@media (min-width: 960px) {
.my-inner::after {
display: none;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row no-gutters my-outer">
<div class="d-flex flex-wrap justify-content-around my-inner">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句