September 28, 2011

CSS Multiple grouped elements with margins

Question by Marty Wallace

Take this HTML:

<div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
</div>

With the companion CSS:

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px;
    background: red;
}

The result of this is four blocks, which have between them 2 pixels of space (1px from the right margin of the left block and 1px from the left margin of the right block).

Is there a way that I can achieve a similar effect to border-collapse? ie. I want there to be only one pixel of margin between adjacent blocks.

This is a basic example of often more complex situations that I run into, and I don’t want to get around it by by anything similar to only setting margin-left to 1 pixel etc.

Answer by Starx

There are multiple ways to this

One of them is

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px 1px 1px 0;
    background: red;
}
div.block:last-child {
    margin: 1px 0 1px 0;
}

Another is

div.block+div.block { margin-left: 1px; }

You can check the demo of both way here

...

Please fill the form - I will response as fast as I can!