Home > Back-end >  How to align a div to be exactly under the middle of another div
How to align a div to be exactly under the middle of another div

Time:08-09

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

CodePudding user response:

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

CodePudding user response:

You could set the width of both divs to be equal and then make them both flexboxes by applying these properties to both of them:

    #dates {
        width: 300px;
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        justify-content: space-around;
    }

    #nums {
        width: 300px;
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        justify-content: space-around;
    }
    
    div div {
        flex: 1;
        text-align: center;
    }
<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>

CodePudding user response:

Maybe this is what your looking for.

I both centered the tekst. So no matter what size the month is he always center it.

#dates div{
    display: inline-block;
    text-align: center;
    width: 20vw;
}
#nums div{
    display: inline-block;
    position: relative;
    margin-top: 10px;
    text-align: center;
    width: 20vw;
}
<body>
   <div>
    <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>
   </div>
</body>

  • Related