Bilal075
Bilal075

Reputation: 85

Keep space / padding between Divs

How would I be able to keep the space between my inlined div elements without counting the space as 'pixels'?

For example, currently i'm using margin-right (as my padding between my elements) but is eventually counting that as pixels (the result shows off ugly, see JsFiddle, div element gets pushed down).

#parent .child
{
    position: relative;
    display: inline-block;
    height: 100%;
    width: 16.5%;
    background-color: green;
    margin-right: 15px;
}

JsFiddle

Basically, I just like to have the first item floaten left and the last item floaten right. Now I know many of you guys are thinking, why not just use the feature 'justify'? I've tried using it, but it isn't a really good option since the amount of elements can be everything (10, 5, 8, etc).

Help would be appericiated!

EDIT: This basically is the feature i'd like to achieve but for multiple elements (instead of having only 1 row, there could be 2-16 rows. enter image description here

Upvotes: 0

Views: 1478

Answers (2)

Oriol
Oriol

Reputation: 288550

If I understand it properly, you want to set an internal margin between the children, but not between the edge children and the parent. Something like

.child { margin-right: 15px; }
.child:last-of-line { margin-right: 0; }

Currently there is no way to do that, but you can add an additional wrapper with a negative margin:

#inner-wrapper {
  margin-right: -15px;
  margin-bottom: -10px;
}
.child {
  margin-right: 15px;
  margin-bottom: 10px;
}

#parent {
  background-color: red;
  overflow: hidden;
}
#inner-wrapper {
  margin-right: -15px;
  margin-bottom: -10px;
}
.child {
  vertical-align: top;
  display: inline-block;
  height: 210px;
  width: 16.5%;
  background-color: green;
  margin-right: 15px;
  margin-bottom: 10px;
}
<div id="parent">
  <div id="inner-wrapper">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

Upvotes: 0

Oriol
Oriol

Reputation: 288550

You can use text-align: justify. It won't justify the last line, but you can force a new line with a pseudo-element:

#parent {
  text-align: justify;
  background-color: red;
}
#parent:after {
  content: '';
  display: inline-block;
  width: 100%;
}
#parent .child {
  display: inline-block;
  height: 100px;
  width: 16.5%;
  background-color: green;
  margin-right: 15px;
  margin-bottom: 10px;
}
<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

Upvotes: 1

Related Questions