Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make equal space between boxes in one row via CSS

Tags:

css

I have a requirement that there are 4 boxes in one row.

  1. the boxes have fixed width and height
  2. but the width of the row will change by screen size.
  3. the first box should be aligned to the left border of the row
  4. last box aligned to right border.
  5. Also the space between any two boxes should be equal.

Is there a pure CSS way to make that happen? Here is the jsfiddle code.

HTML:

<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>

CSS:

.row {
    display: table;
    border: 1px solid green;
    width: 400px; /* it changes by screen size actually */
    padding: 5px;
}
.row:before, .row:after {
    content: "";
}
.row:after {
    clear: both;
}
.col {
    float: left;
    width: 25%;
}
.box {
    border: 1px solid #DDD;
    width: 80px;
    height: 80px;
    margin: 0 auto;
}
.col:first-child .box {
    margin-left: 0;
}
.col:last-child .box {
    margin-right: 0;
}
like image 883
ucdream Avatar asked Feb 12 '23 15:02

ucdream


2 Answers

Use text-align:justify on the container, this way it will work no matter how many elements you have in your div (you don't have to work out % widths for each list item

Updated CSS

.row {
    text-align: justify;
    min-width: 412px;
    border: 1px solid green;
    width: 80%; /* it changes by screen size actually */
    height: 90px;
    padding: 5px;
}

.row:after {
    content: '';
    display: inline-block;
    width: 100%;
}
.col {
    display: inline-block;
}
.box {
    border: 1px solid #DDD;
    width: 80px;
    height: 80px;
    margin: 0 auto;
}

FIDDLE

like image 79
Danield Avatar answered Feb 16 '23 03:02

Danield


You can make use of css3 flex boxes which is supported in modern browsers.

.row {
  display: flex;
  justify-content: space-between;
  border: 1px solid green;
}

.box {
  border: 1px solid #DDD;
  width: 80px;
  height: 80px;
}
<div class="row">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

jsfiddle demo

more about flex boxes @ css tricks

like image 24
T J Avatar answered Feb 16 '23 03:02

T J