Search code examples
htmlcssposition

Allowing parent div to resize when child element is getting bigger


I have a div containing a table , which are centered:

<div class="parent">
 <table class="child">
 </table>
</div>

CSS:

.parent{
 position: absolute;
 width:300px;
 height:200px;
 top:50%;
 left:50%;
 margin:-100px 0 0 -150px;
 background: #fff;
 border: 1px solid #fff;
 border-radius: 5px ;
-moz-border-radius: 5px ;
-webkit-border-radius: 5px ;
 display:inline-block;
 text-align:center;
 }

In case the table its getting bigger than div's size it overlapps it,and i need it to resize parent div too.I believe the absolute position is the problem...is there a way to fix this?


Solution

  • you may use translate and min-width, remove height with absolute :

    .parent{
     position: absolute;
     min-width:300px;/* optionnal*/
     top:50%;
     left:50%;
     background: #fff;
     border: 1px solid #fff;
     border-radius: 5px ;
     text-align:center;
     transform:translate(-50%,-50%);
     }
    .child {
      margin:0 auto;
    }
    td {
      border:solid;
    }
    table:hover td{
      padding:2em;/* demo purpose */
    }
    <div class="parent">
     <table class="child">
       <tr>
         <td>td</td>
         <td>td</td>
         <td>td</td>
       </tr>
       <tr>
         <td>td</td>
         <td>td</td>
         <td>td</td>
       </tr>
     </table>
    </div>

    or use the flex model

    html,body {
      height:100%;
      width:100%;
      }
    body {
      display:flex;
      align-items:center;/* vertical*/
      justify-content:center;/* horizontal*/
      margin:0;
      }
    .parent{
      background: #fff;
      border: 1px solid #fff;
      border-radius: 5px ;
      -moz-border-radius: 5px ;
      -webkit-border-radius: 5px ;
      display:inline-block;
      text-align:center;
    }
    .child {
    
    }
    td {
      border:solid;
    }
    table:hover td{
      padding:2em;
    }
    <div class="parent">
     <table class="child">
       <tr>
         <td>td</td>
         <td>td</td>
         <td>td</td>
       </tr>
       <tr>
         <td>td</td>
         <td>td</td>
         <td>td</td>
       </tr>
     </table>
    </div>