Search code examples
htmlcssalignmentinlinetext-align

How to align a div to be exactly under the middle of another div


I have to lists of data, one with id of dates and other one with id of nums. The number of letters in date and num is not equal so how Can I put each of divs in nums be exactly under dates?

#dates div{
    display: inline-block;
    margin-left: 20px;
}
#nums div{
    display: inline-block;
    margin: 30px;
    position: relative;
    top:-20px;
}
<body>
    <div id="dates">
        <div>Aug 5</div>
        <div>Aug 6</div>
        <div>Aug 7</div>
        <div>September 12</div>
    </div>
    <div id="nums">
        <div>9</div>
        <div>7</div>
        <div>5</div>
        <div>3</div>
    </div>
</body>

For example, in here 3 should go to right because it should be exactly down of the middle of september. I don't need pixel things like margin and left and right. because the nums may change but it must still be in the down of middle of it's date. Thanks


Solution

  • If you can't use a table (and you should), use CSS Tables.

    div {
      text-align: center;
      padding: 1em;
      border: 1px solid red;
    }
    
    #nums,
    #dates {
      display: table-row;
    }
    
    .showwidth {
      display: table-cell;
    }
    <div id="dates">
      <div class="showwidth">Aug 5</div>
      <div class="showwidth">Aug 6</div>
      <div class="showwidth">Aug 7</div>
      <div class="showwidth">September 12</div>
    </div>
    <div id="nums">
      <div class="showwidth">9</div>
      <div class="showwidth">7</div>
      <div class="showwidth">5</div>
      <div class="showwidth">3</div>
    </div>