我正在尝试制作一个具有 4 列的响应式网格,以填充桌面版屏幕的整个宽度,但是添加边距以将它们隔开显然意味着最后一列没有填充屏幕的剩余宽度,或下降到新行,具体取决于给定的列宽。
CSS:
#servicesGrid
{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
.service
{
width:24.75%;
height:45%;
background:#262626;
display:block;
float:left;
margin:1px;
}
#servicesGrid .service:nth-of-type(1)
{
width:100%;
}
#servicesGrid .service:nth-of-type(2)
{
margin-left:0;
}
#servicesGrid .service:nth-of-type(5)
{
margin-right:0;
}
HTML:
<div id="servicesGrid">
<div class="service"></div>
<div class="service"></div>
<div class="service"></div>
<div class="service"></div>
<div class="service"></div>
</div>
JSFiddle 上的示例:https://jsfiddle.net/4bw4p3LL/ .
最佳答案
如果您使用 %
作为 width
,我建议您也使用 %
作为边距。所以你会确定你加起来 100%
。
想法是 4*colwidth + 3*margins = 100%
因此,对所有 .col
元素使用 margin-right:0.5%
除了最后一个元素 ( nth-of-type(5)
) ,那么你的宽度将是 100% - 3*0.5% = 98.5%/4 = 24.625%
其中:100%
是servicesGrid
的宽度,3
是0.5%
边距的数量给定前 3 个列,98.5%
是第 4 个列占用的剩余空间,用它除以列的 nr 得到每个列的宽度
#servicesGrid
{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
.service
{
width:24.625%;
height:45%;
background:#262626;
display:block;
float:left;
margin:1px 0.5% 1px 0;
}
#servicesGrid .service:nth-of-type(5)
{
margin-right:0;
}
<div id="servicesGrid">
<div id="serviceWide" class="service col" style="width:100%; margin:0 0 1px 0">
</div>
<div class="service col"></div>
<div class="service col"></div>
<div class="service col"></div>
<div class="service col"></div>
</div>
关于html - CSS 全宽网格 - 具有均匀边距的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39897981/