0

Here's an SO question about exactly this, and I've found several others. Many of them have a dozen answers, using many (many!) combinations of align and justify styles, transforms, margins, references to table cells, etc.

I've tried maybe 200 combinations of ideas from references. Is it possible to center the text vertically? Is it possible to do it while maintaining 100% height without adding divs around or inside the boxes?

My main finding after all this is that height: 100% thwarts every other style that can succeed. For example, margin-top and margin-bottom set to auto works, but not with 100% height.

section {
  height: 400px;
}

#boxes {
  background-color: green;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 6px;
  height: 100%;
  min-height: 10em;
  min-width: 12em;
}

#boxes>div {
  background-color: #8ca0ff;
  text-align: center;
  border: 1px solid red;
  height: 100%;
}
<section>
  <div id="boxes">
    <div id="00">I'm not</div>
    <div id="01">vertically</div>
    <div id="02">centered.</div>
    <div id="10">I</div>
    <div id="11">am not</div>
    <div id="12">either!</div>
    <div id="20">Was CSS designed</div>
    <div id="21">by a psychopath?</div>
    <div id="22">Seems like it!</div>
  </div>
</section>

I am astonished at how non-simple this simple-seeming thing is.

goodson
  • 727
  • 2
  • 14
  • 24

1 Answers1

1

Put flex on the boxes, just like in an answer on the post you linked.

https://css-tricks.com/snippets/css/a-guide-to-flexbox

section {
  height: 400px;
}

#boxes {
  background-color: green;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 6px;
  height: 100%;
  min-height: 10em;
  min-width: 12em;
}

#boxes>div {
  background-color: #8ca0ff;
  text-align: center;
  border: 1px solid red;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
<section>
  <div id="boxes">
    <div id="00">I'm not</div>
    <div id="01">vertically</div>
    <div id="02">centered.</div>
    <div id="10">I</div>
    <div id="11">am not</div>
    <div id="12">either!</div>
    <div id="20">Was CSS designed</div>
    <div id="21">by a psychopath?</div>
    <div id="22">Seems like it!</div>
  </div>
</section>
isherwood
  • 58,414
  • 16
  • 114
  • 157