Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto space between horizontal divs in CSS

Tags:

html

css

I've searched a lot but I was not lucky to find a solution to what I am after!

Here is the issue: I've created a master div (width 100%) and within it there are several inner divs. You can see it here: http://jsfiddle.net/EAkLb/1/

HTML:

<div class="section_zone">
    <div class="box_frame" id="_15">inner box 1</div>
    <div class="box_frame" id="_15">inner box 2</div>
    <div class="box_frame" id="_15">inner box 3</div>
    <div class="box_frame" id="_15">inner box 4</div>
</div>

What I am trying to accomplish is to auto the space-width between the inner divs.

the first-child is aligned to left, and the last-child is aligned to the right, but as you can see, the space between the other divs is not the same.

I hope the following demonstration image be helpful to explain what I am after exactly:

demonstration image

Please Note: in the fiddle, I've added 4 inner divs but, the solution I'm after should work no mater how many divs I have (e.g. 2, 3, 4, 5, ...etc) divs.

Thanks in advance for your help.

like image 650
SULTAN Avatar asked Jan 15 '14 00:01

SULTAN


2 Answers

Here is JSFiddle

Assume that you have 100% and you have 4 pieces. 4 pieces means you have 3 margin-left block so, when you make your div 22*4=88 then 100-88=12 then 12/3=4 then your margin-left must be:4

div.box_frame{
    float: left;
    background-color: #eee; /* standard background color */
    border: 1px solid #898989; 
    border-radius: 11px;
    padding: 2px;
    margin-left:4%;
    text-align: center;
    /* change border to be inside the box */
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
div.box_frame:first-child{
    margin-left: 0;
}
div.box_frame#_15{ /* width 15% */
    width: 22%;
}

So if you use less variables then you can use this solution without depending on number of div blocks

like image 153
Mehmet Eren Yener Avatar answered Oct 21 '22 23:10

Mehmet Eren Yener


First and foremost, you cannot use the same ID more than once per HTML page.

Secondly, you are on the right track. Just use a margin-right on every element, then proceed to add a psuedo-class of last-child and set margin to 0.

http://jsfiddle.net/EAkLb/1/

To make it work that way for any amount of divs, it would be best practice to still establish a percentage that makes sense. (ie 25% for 4, 33% for 3, 16.6% for 6, etc)


EDIT:

This here would be a much better way to do it (try resizing the window):

http://jsfiddle.net/EAkLb/5/

like image 30
Nicholas Hazel Avatar answered Oct 21 '22 22:10

Nicholas Hazel