Nacht
Nacht

Reputation: 3494

Grid of elements with no margin around the outside

Seems like a simple thing, but I can't seem to find the right search keywords to help me out. I'm half expecting this to be a duplicate.

How do I make a grid of html elements that have margins on the inside, but not on the outside, like so (blue are normal elements with content, black are the margins):

enter image description here

Instead of this:

enter image description here

I've found a hacked up method of doing the sides using

:nth-child(4n-3){margin-left:0}
:nth-child(4n){margin-right:0}

but there has to be a better way of doing this. I thought display:table-cell might help me but it doesnt seem to help. This is not for tabular data.

Here is my original rough source code but am quite open to using any structure:

<style>
.foo
{
    float: left;
    clear: left;
    background-color: #b4c6e7;
    margin: 10px;
}
.foo+.foo
{
    clear: none;
}
.bar
{
    background-color: black;
}
</style>
<div class="bar">
    <div class="foo">content</div><div class="foo">content</div><div class="foo">content</div><div class="foo">content</div>
    <br/>
    <div class="foo">content</div><div class="foo">content</div><div class="foo">content</div><div class="foo">content</div>
    <br/>
    <div class="foo">content</div><div class="foo">content</div><div class="foo">content</div><div class="foo">content</div>
    <div style="clear:both" />
</div>

Upvotes: 0

Views: 59

Answers (1)

David Waters
David Waters

Reputation: 12028

You can use first-child and last-child to override the borders, like the following very quick code.

I have used a table as you say this data should be displayed in a grid. The same effect can be used for similar effect, but tables start off shaped in a grid so are easy to demo.

Background colors are added so you can easily see which styles are applying to which cells.

.datagrid {
    border-spacing:0px;
    border:0px;
    margin:0px;
    padding:0px;
    background-color:purple;
}

.datagrid td{
    border:1px solid black;
    background-color:blue;
    margin:0px;
    padding:10px;
}

.datagrid tr td:first-child {
    background-color:red;
    border-left:0px;
}

.datagrid tr td:last-child {
    background-color:green;
    border-right:0px;
}

.datagrid tr:first-child td {
    border-top:0px;
    background-color:yellow;
}

.datagrid tr:last-child td {
    border-bottom:0px;
    background-color:yellow;
}
<table class="datagrid" >
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

See https://jsfiddle.net/jec2gcg2/ for the working example.

Upvotes: 1

Related Questions