nickck15 nickck15 - 2 months ago 10
CSS Question

CSS Full-Width Grid - Columns with Even Margins

I'm trying to make a responsive grid with 4 columns that fills the whole width of the screen on the desktop version, but adding margins to space them out in-between obviously means that the last column either doesn't fill the remaining width of the screen, or drops down into a new row, depending on the widths the columns are given.

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>


Example on JSFiddle: https://jsfiddle.net/4bw4p3LL/.

Answer

if you use % for width , i suggest you use % for margins also. so you will be sure you add up to 100% .

the idea is that 4*colwidth + 3*margins = 100%

so, using a margin-right:0.5% to all .col elements except the last one ( nth-of-type(5) ) , then you will have the width of 100% - 3*0.5% = 98.5% / 4 = 24.625%

where: 100% is the width of the servicesGrid, 3 is the number of 0.5% margins given to the first 3 cols, 98.5% is the remaining space occupied by the 4 col, and dividing it by the nr of col gives you the width of every col

#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>