How to not make external margins for floats in a div

advertisements

I am learning HTML / CSS basics and I am stuck at the following problem.
I would like to put 3 fixed-size float divs in a fixed-width outside div, and I would only like to have margins between them, not outside them.

My problem is that I don't know how to achieve this. I tried reading about margin-collapse and negative margins but it is quite hard for me to understand.

I have put my example onto the following jsfiddle: http://jsfiddle.net/6dqR6/

HTML

<div class="outer">
    <div class="articles">
         <h2>header</h2>

        <div class="article">
            <p>1</p>
        </div>
        <div class="article">
            <p>2</p>
        </div>
        <div class="article">
            <p>3</p>
        </div>
        <div class="article">
            <p>4</p>
        </div>
        <div class="article">
            <p>5</p>
        </div>
        <div class="article">
            <p>6</p>
        </div>
    </div>
</div>

CSS

.outer {
    width: 940px;
    margin: 0 auto;
}
.articles {
    height: 1500px;
    background-color: #fcdda1;
}
.article {
    width: 300px;
    height: 350px;
    float: left;
    background-color: #4ecac3;
    margin: 0 20px 20px 0;
}

Can you tell me:

  1. What is the recommended way to solve my problem and fix the above example?
  2. Possibly some beginner friendly articles/books from which I could learn about it?

Thanks a lot, and sorry for asking such a beginner level question here.


1) Solution for a basic CSS knowledge

Based on Css2, fully cross-browser

Here is the solution to have only the inner margin, and not applied to the last on the right, click here, the working fiddle.

You have to make a mask to overflow the plus margin:

.outer {
  width: 940px;
  overflow:hidden;
  /*behaves like a mask*/
}
.articles {
  width: 960px; /*set the actual width: 320*3*/
}

2) Advanced solution

Based on Css3, only modern browser (except, of course, IE)

The Css nth-child solution is here in this example: jsfiddle.net:

.articles > :nth-child(3n+1) { margin-right: 0; }

You can find here the complete explanation about how it works.

Since IE have a partial support of Css3 upcoming standards, you can use IE conditional Comments to pass specific Css on for InternetExplorer legacy versions (e.g. Css3 Solution for modern browsers, Css2 solution only for old IEs).

Eventually, here are other solutions based on Css pseudoclass and jQuery.

3) Online resources to make practice on CSS

Here is where you can learn a lot about Css in general:

CssTricks

Smashing Magazine

Tuts Plus: CSS categories