Make divs have a 20% width with padding in between each, but not to the left of the first or the right of the last

StackOverflow https://stackoverflow.com//questions/25088133

Question

Let's say I've got this layout to build:

Assuming the text and the grid are within the same div, and therefor share a width of about 990px, how can I dynamically make this grid have equal width columns, without fixed widths?

I could set each div to width:20%, but then they'd line up directly next to each other instead of spaced out. http://jsfiddle.net/97H3P/

I could set each div to width: 20%, box-sizing: border-box, and padding: 0 20px, but then there would be a 20px gap between the edge of the lines and the edge of the first and last div. http://jsfiddle.net/97H3P/1/

I could set up each div to box-sizing: border-box;, width: 20% and padding-right: 20px, and then on the 5th div, set padding-right: 0;, but then the fifth div is wider than the rest. http://jsfiddle.net/97H3P/2/

I could set the first four divs of each row to box-sizing: border-box;, width:20.8%, the fifth to width: 16.8%, and then padding-right: 20px to all of them, but that math only works out at the 990px width. http://jsfiddle.net/97H3P/3/

Is there a better way to do this? I can't find any elegant solution.

Thanks.

Update: For a few minutes, I was interested in CSS3's column-count feature, but then I realized it only does top to bottom, not left to right, which is how I need this ordered.

Was it helpful?

Solution

Here's a non-Boostrap example I've sketched quickly.

Even though it uses the Bootstrap classes.

The trick is achieved by using the position: relative and box-sizing: border-box

It is also kinda responsive.

OTHER TIPS

You should take a look at flexbox http://css-tricks.com/snippets/css/a-guide-to-flexbox/

How about using some extra divs as spacers? Fiddle

HTML

<div></div>
<div class="spacer"></div>
<div></div>
<div class="spacer"></div>
<div></div>
<div class="spacer"></div>
<div></div>
<div class="spacer"></div>
<div></div>

CSS

div {
    background: #000;
    height: 200px;
    float: left;
    opacity: 0.2;
    width: 18%;
}

div.spacer{
    opacity: 1;
    width: 2.5%;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top