Flexbox - center text vertically

Skrodde picture Skrodde · Jan 30, 2017 · Viewed 21.4k times · Source

I have a square-shaped flexbox, that is completely covered with one hyperlink.

Now I want to vertically center the content of the flexbox.

However, using a div element with the property display: table and a nested div with the property display: table-cell; vertical-align: middle does not work, since I lose the square shape.

If I use divs instead of ul and li I lose the property of being able to click everywhere.

I would like "Text" to be aligned in the horizontal and vertical center of the red box:

body {
  margin: 0px;
  width: 100%;
}
main {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.flex-container {
  width: 100%;
}
ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  -webkit-padding-start: 0px;
  -webkit-margin-before: 0px;
  -webkit-margin-after: 0px;
}
li {
  display: flex;
  flex-direction: column;
  width: 50%;
}
.red {
  background-color: red;
}
.white {
  background-color: white;
}
.tile:before {
  content: '';
  float: left;
  padding-top: 100%;
}
.tile {
  text-align: center;
}
<main>
  <div class="flex-container">
    <ul>
      <li class="red">
        <a href="/">
          <div class="tile">
            Text
          </div>
        </a>
      </li>
    </ul>
  </div>
</main>

Answer

Michael Benjamin picture Michael Benjamin · Jan 30, 2017

main {
  height: 200px;
  width: 200px;
}
a {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: red;
  height: 100%;
}
<main>
  <a href="/">
    <div class="tile">Text</div>
  </a>
</main>