Thứ Ba, 22 tháng 3, 2011

Avoiding Excess Margin on Repeating Columns

Avoiding Excess Margin on Repeating Columns

Tags:
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.
Uneven Columns with CSS
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.
Uneven Columns with CSS

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 class="container">
<ul class="col3">
 <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!

Related Posts

Không có nhận xét nào:

Đăng nhận xét