Question

I'm trying to make an elastic layout which aligns both the left and the right margins with the far left and far right of the page, no matter how many items are shown on that line.

This is my code: http://jsfiddle.net/U2W72/1/

.thumb {
    float: left;
    width:16%;
    margin-left: 2%;
    margin-right: 2%;
    margin-bottom: 4%;
    background: pink;
    height: 200px;
}
.thumb:nth-child(5n) {
    margin-right: 0px;
    box-shadow:inset 0 0 0 3px red;
}
.thumb:nth-child(5n+1) {
    margin-left: 0px;
    box-shadow:inset 0 0 0 3px blue;
}
@media (max-width: 1200px) {
    .thumb, .thumb:nth-child(1n) {
        width:21%;
        margin-left: 2%;
        margin-right: 2%;
        margin-bottom: 4%;
        box-shadow: 0 0;
    }
    .thumb:nth-child(4n) {
        margin-right:0;
        box-shadow:inset 0 0 0 3px yellow;
    }
    .thumb:nth-child(4n+1) {
        margin-left:0;
        box-shadow:inset 0 0 0 3px blue;
    }
}
@media (max-width: 600px) {
    .thumb, .thumb:nth-child(1n) {
        width:46%;
    }
    .thumb:nth-child(2n) {
        margin-right:0;
        box-shadow:inset 0 0 0 3px gray;
    }
    .thumb:nth-child(2n+1) {
        margin-left:0;
        box-shadow:inset 0 0 0 3px blue;
    }
}
@media (max-width: 400px) {
    .thumb, .thumb:nth-child(1n) {
    width:100%;
    display:block;
    margin:0;
    box-shadow: inset 0 0 5px 1px;
    }
}
#left {
    float: left
}
#right {
    float: right
}

I believe I am using nth child correctly to remove the margin from the left and right most pink boxes so they align but it doesn't look correct when I run it. Can anyone show me where I am going wrong please?

Was it helpful?

Solution

When you remove the margins from first and last element on the row, total of widths+margins isn't 100%. Example: if you have 5 boxes with width 16% and margin left and right 2%, then total is 100%. But when you remove 2% margin from first box and 2% margin from last box, then total is 96%. Make sense?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top