Phone: 406-788-9165

CSS Tricks : Perfect Multi-column Divs

It is sometimes frustrating to get perfect columns with CSS and use them in a responsive mobile/tablet design or a liquid desktop design.

Consider the following for a 3 column design:

CSS

.columns {
	width: 100%;	
}
.column {
	width: 33%;
	float: left;
	margin: 20px;
	padding: 10px;
	border: solid 1px red;
	min-height: 100px;
	text-align: center;
}
.clear {
	clear: left;	
}

HTML

<div class="columns">
	<div class="column">Column 1</div>
	<div class="column">Column 2</div>
	<div class="column">Column 3</div>
</div>
<div class="clear"></div>

Result:

Column 1
Column 2
Column 3

The Problem: When you try to create any number of percent width columns where they add up to 100% and use margin, the last column always spills onto the next line.

Why does this happen? Because the box model calculates the percent of the parent div's width, but does not consider margins or padding in this computation.

The Solution: Put each column into it's own container div and give that div the desired width percent, floating, AND 0 margin. Put your margin, padding and other things in the regular .column class.

CSS

.columns {
	width: 100%;	
}
.column-cont {
	width: 33%;
	margin: 0;
	float: left;
}
.column {
	margin: 20px;
	padding: 10px;
	border: solid 1px red;
	min-height: 100px;
	text-align: center;
}
.clear {
	clear: left;	
}

HTML

<div class="columns">
	<div class="column-cont"><div class="column">Column 1</div></div>
	<div class="column-cont"><div class="column">Column 2</div></div>
	<div class="column-cont"><div class="column">Column 3</div></div>
</div>
<div class="clear"></div>

Result:

Column 1
Column 2
Column 3


Revision History:

Nov 4, 2015: .column class must not have a width specified to get perfect width columns.



Published by: Thomas Penwell
Initially published on: August 8, 2015
Article last modified on: Sunday, August 14, 2016.

Home - Web Portfolio - Web site Tools - Database Design Service - Consulting
Web Design Service - Web Hosting Solutions - Service Rates
Client Login - Contact Us - Promotions - Partners - Articles - Perl Scripts


Our Sites:
restaurantorderpad.com