1

I would like to create a grid of squares with their content centered:

#all {
  display: grid;
  grid-template-rows: 200px;
  grid-template-columns: 200px 20px 200px;
}

.disp {
  background-color: black;
  color: white;
  border-color: gray;
  border-width: 10px;
  border-style: solid;
  @import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600,700,800');
  font-family: 'Open Sans', sans-serif;
  font-size: 120px;
  font-weight: bolder;
  padding: 0 20px 0 20px;
  align-self: center;
  justify-self: stretch;
}
<div id="all">
  <span class="disp hour">9</span><span class="sep"> </span><span class="disp min">27</span>
</div>

I cannot make the 9 centered and preserve the 200px width at the same time. Replacing the last CSS line with justify-self: center; does center the 9, but also reduces the width of the cell to make it fit. The width of the grid is preserved.

How to say "center and expand to the width of the cell" in CSS Grid?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • `text-align: center;` ? – Temani Afif Aug 08 '18 at 08:21
  • 1
    @TemaniAfif: that was it, thanks. I believe that I also understood that `justify-self` is just about how the container of the cell will behave (fit and left, fit and right, stretched), independently of the positioning of the content.Would you mind turning this into an answer? – WoJ Aug 08 '18 at 08:29
  • yes exactly, justify-self is to center the whole element and what you need is to cented what is inside the element – Temani Afif Aug 08 '18 at 08:31

2 Answers2

0

All you need is text-align:center

Add this in your CSS code:

If you want only 9 centered:

.hour {
   text-align:center;
}

If you want both centered:

.disp {
   text-align:center;
}

Tested in Chrome Inspect Element.

Same trick works with the .min class too.

Hope this helps.

Hamza Ahmad
  • 512
  • 2
  • 7
  • 32
0

This will work:

  .hour {
      text-align:center;
    }
codeVerses
  • 231
  • 1
  • 6