user419017
user419017

Reputation:

Good way to center evenly margin divs within container?

What I'm trying to do is center an x amount of divs within a container, and have a margin on each side of the divs of 14px

But, code like this:

divs{
  display: inline-block;
  margin: 0 7px;
}

Will produce a margin of 7px on the outside of the two outer divs, along with the even margins on the inner side of each div. What is generally good practice to combat this? I was thinking apply a 'last' class to the last div and give it margin-right: 0, while the rest have margin-right: 14, but that seems messy.

fiddle: http://jsfiddle.net/ZMqbW/3/

Upvotes: 0

Views: 97

Answers (2)

Ana
Ana

Reputation: 37178

I don't think it is very elegant, but text-align: center on the container works for this.

EDIT: test http://dabblet.com/gist/2793852

Upvotes: 1

Oleg
Oleg

Reputation: 9359

Suggestion #1

What prevents you from adding a padding to the container?

.container {
    padding: 7px;
    overflow: hidden;
}
.divs {
    display: block;
    float: left;
    margin: 0 7px;
}

Also please note, that Internet Explorer doesn't like inline-block too much, so I'm using float: left; in combination with overflow: hidden; on the container.

You can try this fiddle and see if it works for you.

Suggestion #2

Another suggestion would be to use pseudo-classes like so:

.divs:first-child {
    margin-left: 14px;
}
​.divs:last-child {
    margin-right: 14px;
}​​​​​​​​​​

Try this fiddle to see it in action.

Upvotes: 0

Related Questions