Joseph Silber
Joseph Silber

Reputation: 219936

Evenly spaced fixed-width columns - in a responsive setting

I'm trying to create some evenly spaced columns (an ol), with the columns themselves being fixed width.

So far, I've managed to achieve the desired effect by using table layout, and nesting an additional element inside the list item.

HTML:

<ol>
    <li><div></div></li>
    <li><div></div></li>
    <li><div></div></li>
    <li><div></div></li>
    <li><div></div></li>
</ol>​

CSS:

ol {
    display: table;
    width: 100%;
}

li {
    display: table-cell;
}

div {
    margin: 0 auto;
    width: 100px;
    height: 250px;
}

This works great, but has the following 2 shortcomings:

  1. As you can see in the demo, the first & last columns don't line up flush with the parent's outer edges.
  2. This can't really be used responsively. The only thing you can do at smaller widths is stack them, but I'd like to split them (2 or 3 per row).

Is what I'm after even possible in CSS alone? I know there are a plethora of ways to accomplish this in JS, but I'm after a CSS-only solution.


P.S. I don't care about IE7-, but I do need to support IE8. CSS3 selectors are OK though, since I'm anyhow using selectivizr in the project (I know that's JS ;-)).

Upvotes: 2

Views: 2811

Answers (2)

Oleg
Oleg

Reputation: 24988

It seems appropriate for you to recycle "how to *really* justify a horizontal menu". Basically the behaviour you're describing is that of inline-block elements of identical width having text-align:justify applied:

ol {
  /*force the desired behaviour*/
  text-align: justify;
  /*remove the minimum gap between columns caused by whitespace*/
  font-size: 0;
}

li {
  /*make text-align property applicable*/
  display: inline;
}

/*force "justify" alignment that requires text to be at least over 2 lines*/
ol:after {
  content: "";
  display: inline-block;
  position: relative;
  width: 100%;
  height: 0;
}

div {
  display: inline-block;
  width: 100px;
  height: 250px;
}

Working fiddle.

NB: you may have to re-apply desired font-size and text-align to descendants of ol depending on the reset you're using (i.e. to prevent these properties from being inherited)

Upvotes: 2

Jamie Paterson
Jamie Paterson

Reputation: 446

Ok my first thought would be to use media queries to gain a responsive approach for how many you want to show per row on differing screen sizes and my second would be to use

     box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;

this will stop the paddings you may put in later adding onto the box model size.

Hope this is close to what you are after.

Upvotes: 0

Related Questions