Search code examples
htmlcss

How to center grid elements?


I tried to use flex to center my grid, but it feels unelegand and cringe. At the same time left:50%; transform: translateX(-50%); works but breaks the grid. Simple margin isn't adaptive enough. Is there any RIGHT way to do it?

justify-items:center; --> it's centered only inside the grid, but not the grid itself

.calendar__wrapper{
    font-size:20px;
    position:relative;
    display:flex; /* is this normal?*/
    justify-content: center;
}
.calendar__inner{ 
    display:grid;
    grid-template-columns:  repeat(7, 1fr);
    grid-template-rows:  repeat(7, 1fr);
    position:absolute;
    /* left:50%; shouldn't use idk why
    transform: translateX(-50%); */
    justify-items:center; 

Solution

  • Centering the grid itself is not the problem there.. since it's perfectly legit to use the flex approach to center it relative to the container.

    But here I decided to submit a full answer just for the sake of simplifying your approach:

    • remove grid-template-rows: repeat(7, 1fr); since you don't need fixed rows;
    • use grid-auto-rows: min-content; to adapt grid height to its content;
    • get rid of relative/absolute positioning.. so the parent container as a block level element will have its size ruled by its content without messing with the general flow;
    • have a css rule for the .calendar__inner inner items (days);
    • get rid of justify-items:center on the grid

    .calendar__wrapper{  
      display: flex;
      justify-content: center;
      
      font-size:20px;        
    }
    .calendar__inner{   
      display: grid;
      grid-template-columns: repeat(7, 1fr);  
      gap: .25em;
      grid-auto-rows: min-content;
    }
    
    .calendar__inner *{
      border: solid 1px;
      text-align: center;
    }
    
    /*border related rules...*/
    
    .border{
      border: solid 1px;
    }
    
    .red{
      border-color: red;
    }
    
    .green{
      border-color: green;
    }
    
    .purple{
      border-color: purple;
    }
    <div class="calendar__wrapper border red">
      <div class="calendar__inner border green">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        
        <div>8</div>
        <div>9</div>
        <div>10</div>
        <div>11</div>
        <div>12</div>
        <div>13</div>
        <div>14</div>
        
        <div>15</div>
        <div>16</div>
        <div>17</div>
        <div>18</div>
        <div>19</div>
        <div>20</div>
        <div>21</div>
        
        <div>22</div>
        <div>23</div>
        <div>24</div>
        <div>25</div>
        <div>26</div>
        <div>27</div>
        <div>28</div>
      </div>
    </div>