Avoiding Excess Margin on Repeating Columns

Avoiding Excess Margin on Repeating Columns

Avoiding Excess Margin on Repeating Columns

Creating columns in CSS is not very hard to achieve but when working with a dynamic site and if the CMS does not allow you to easily modify each column accordingly, you end up with a set of excess margin. Below is a common example of what I’m talking about.

Normally you can just specify the last column to take away the excess margin, but what if you were working in a system where it didn’t allow you to easily customize each column in the html or the columns were being displayed dynamically?

The Solution

By wrapping the unordered list and hiding the excess margin, we are able to go around this issue.

HTML

Wrap the unordered list with another div and specify the container width. The trick is to add an overflow:hidden; to hide the excess 10px margin to the right.

<div>
<ul>
	<li>
		<h2>Column 1</h2>
	</li>
	<li>
		<h2>Column 2</h2>
	</li>
	<li>
		<h2>Column 3</h2>
	</li>
</ul>
</div>

CSS

Now calculate the padding and margin as it fits within your column. If you were to calculate the max width of 970px for a three column layout:
(Max Width + Right Margin) / # of Columns – (L and R Padding + Right Margin) = Column Width
(970px + 10px) / 3 – (40px +10px) = 276px

.container {
	margin: 0 auto;
	width: 970px;
	overflow: hidden;
}
ul.col3 {
	width: 980px;
	margin: 20px 0;
	padding: 0;
	list-style: none;
	float: left;
}
ul.col3 li {
	float: left;
	background: #fff;
	width: 276px;
	padding: 10px 20px;
	margin: 5px 10px 5px 0;
}

Conclusion

This is just a ‘work-around’ trick I use when trying to avoid excess margins on repeating columns. It would be ideal to use the :first-child and :last-child pseudo-classes in these situations, but until its supported by all major browsers, I felt this was simple enough to use. If you have any better solutions or techniques, please let me know!

 

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>