zok
zok

Reputation: 7892

Fluid width with equally spaced DIVs (also from container)

I want to achieve this, using only HTML/CSS:

equally spaced divs (also from container)

Much like this or this, except that they must be equally spaced also from the container.

Upvotes: 0

Views: 76

Answers (3)

AndrewTet
AndrewTet

Reputation: 1182

If the items you need the space between have a defined width and you don't need IE8 support, you can use calc() to do this (http://caniuse.com/#search=calc).

Just add the following margin-left to the child elements.

/* X = number of containers */
/* Y = container width (needs to be defined) */
/* Z = number of spaces (usually X + 1) */
margin-left: calc((100% - (X * Y)) / Z);

Codepen: http://codepen.io/supah_frank/pen/OPMrvZ

Upvotes: 1

Madbreaks
Madbreaks

Reputation: 19539

Here's one probably terrible way to do it.

body { width:100%; border:solid 1px blue; margin:0; padding:0; }
div { background:red;
      height:60px;
      width:300px;
      display:inline-block;
      position:relative;
      margin-left:-225px;
}
div.a {left:25%;}
div.b {left:50%;}
div.c {left:75%;}
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>  

Then adjust the (negative) margin-left value to 3/4 the width of your divs.

Upvotes: 0

zok
zok

Reputation: 7892

I came up with this, based on Bootstrap's grid:

HTML

<div class="container">
    <div class="row">
        <div class="col">
          <div class="box"></div>
        </div>
        <div class="col">
          <div class="box"></div>
        </div>
        <div class="col">
          <div class="box"></div>
        </div>
        <div class="col">
          <div class="box"></div>
        </div>
    </div>
</div>

CSS (SCSS)

$gutter: 100px;

* { box-sizing: border-box; }

body { margin: 0; padding: 0; }

.container {
  width: 100%;
  padding-left: $gutter/2;
  padding-right: $gutter/2;

  background: lightgrey;
  height: 75px;
}
.row {
  //margin-left: -$gutter/2;
  //margin-right: -$gutter/2;
}
.col {
  float: left;
  padding-left: $gutter/2;
  padding-right: $gutter/2;
  width: 25%;

  //border: 1px solid blue;
  background: lightgray;
  height: 50px;
}

.box {
  width: auto;
  background: red;
  height: 25px;
}

Sample

Upvotes: 0

Related Questions