4

I need to align these divs so that the space between "content1" and the red div equals the space between "content4" and the red div. I don't mind changing the blue-div's margin but this should work for any width.

I used to achieve this by making the width of the 4 blue divs + their left and right margins = 100% but that doesn't seem to work well in this case.

I also tried adding another div inside the red one that contained all the blue divs and giving it margin: 0 auto but that's not working either.

Code in jsfiddle (updated)

PS: if i'm not clear enough, please feel free to edit my question.

Eric Platon
  • 9,819
  • 6
  • 41
  • 48
FranLegon
  • 87
  • 1
  • 2
  • 9
  • What are we allowed to adjust? Are the width or margins adjustable? Do you have an image of what the expect result shoudl be? – Paulie_D Feb 20 '15 at 14:17
  • @Paulie_D you can adjust blue-div's margins but not the width. They will have an image but i can handle that later. – FranLegon Feb 20 '15 at 14:41

3 Answers3

8

You can use the incredible property box-sizing: border-box; supported by all modern browser, IE8 included! And set the width and margin on % :

.red, .blue {
    -moz-box-sizing:    border-box;
    -webkit-box-sizing: border-box;
    box-sizing:        border-box;
}

.red {
    width:650px;
    height:1000px;
    background:red;
    padding: 1% 0 0 1%; // Space top and left of red
}

.blue {
    height:200px;
    width: 24%;
    background:blue;
    display:inline-block;
    float: left;
    margin: 0 1% 1% 0; // Space bottom and right of each blue
}

http://jsfiddle.net/Pik_at/L7qpgdkk/3/

Pik_at
  • 1,459
  • 9
  • 14
3

Hmmm, its quite easy. Check this out

HTML

<div class="red">
    <div class="blue"><div>content1</div></div>
    <div class="blue"><div>content2</div></div>
    <div class="blue"><div>content3</div></div>
    <div class="blue"><div>content4</div></div>
    <div class="blue"><div>content5</div></div>
    <div class="blue"><div>content6</div></div>
</div>

CSS

.red {
    width:680px;
    height:1000px;
    background:red;
}

.blue {
    width: 25%;
    display:inline-block;
    margin-right: -4px;
    box-sizing: border-box;
    padding: 1%;
}

.blue > div {
    background:blue;
    height:200px;
}

Fiddle this.

raju
  • 382
  • 1
  • 11
2

Your calculation is wrong: (20% * 4) + (1% * 4) = 88%.

You have to set top / left margin to 4% so width will be: 80% + (5 * 4%) = 100%.

Added also font-size: 0 to correct inline-block problem with white spacing.

.blue {
    margin: 4% 0 0 4%;
}

Fiddle: http://jsfiddle.net/L7qpgdkk/1/

Reference: Fighting the Space Between Inline Block Elements

emmanuel
  • 9,607
  • 10
  • 25
  • 38