html - CSS 全宽网格 - 具有均匀边距的列

标签 html css grid

我正在尝试制作一个具有 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的宽度,30.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/

相关文章:

javascript - 将字符串与模板中的范围变量连接起来

javascript - 为什么我的js函数不起作用?

jquery - 可调整的 div 大小

c# - WPF - 通过调整大小在窗口中调整控件大小

html - 下拉菜单未对齐

javascript - jquery 中点击切换按钮

javascript - 为视觉元素的继承和重用而设计

html - 构建圆形百分比图表

css - 如何使用 css 网格实现带有空单元格的 2 x 2 布局?

javascript - 使用 JavaScript 从网格数组中删除列