Search code examples
htmlcsswidthcss-tables

Multiple divs with margin to fill parent width


I tried to make multiple divs to take up the whole width from the parent div. In order to do that I used display:table and display:table-cell. The problem with this method is that I can't add margin to the child divs in order to give some space between them. Now they are all stack together and it doesn't look good.

Any suggestions?

Here's the code:

.parent {
      text-align:center;
      margin:0px;
      width:500px;
      padding:0px;
      background:blue;
      display:table;
      box-sizing:border-box;
      -moz-box-sizing:border-box;
      -webkit-box-sizing:border-box;
      list-style-type:none;
    }
    
.child{
      padding:15px;
      background:#f00;
      display:table-cell;
      list-style-type:none;
    }
    
.child:nth-child(2n) {background:green;}
<div class="parent">
<div class="child">sometext</div>
<div class="child">somemoretext</div>
<div class="child">sometext</div>
<div class="child">sometext</div>
</div>


Solution

  • Flexbox got you :) :

      Body {background:cyan;}
    .parent {
      text-align:center;
      margin:0px;
      width:100%;
      padding:0px;
      background:blue;
      display: -webkit-box;
      display: -webkit-flex;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: justify;
      -webkit-justify-content: space-between;
      -ms-flex-pack: justify;
     }
        
    .child{
      padding:15px 25px;
      background:#f00;
      list-style-type:none;
      width:inherit;
      margin:5px;
    }
    
    .child:nth-child(2n) {background:green;}
       <div class="parent">
    <div class="child">sometext</div>
    <div class="child">somemoretext</div>
    <div class="child">sometext</div>
    <div class="child">sometext</div>
    </div>
    <div class="parent">
    <div class="child">somemoretext</div>
    <div class="child">sometext</div>
    </div>
    <div class="parent">
    <div class="child">somemoretext</div>
    <div class="child">somemoretext</div>
    <div class="child">sometext</div>
    </div
    
    >