Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox - center text vertically [duplicate]

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>
like image 256
Skrodde Avatar asked Jan 30 '17 15:01

Skrodde


People also ask

How do I vertically align text in the middle of a div?

Using the Line-Height Property In most cases, you can also center text vertically in a div by setting the line-height property with a value that is equal to the container element's height.


2 Answers

In your .tile delcaration, you need the flexbox code as follows:

justify-content: center;
display: flex;
align-items: center;

You LI declaration should just be display:block as it is not using the flexbox properties.

like image 105
Zack Kirby Avatar answered Oct 24 '22 07:10

Zack Kirby


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>
like image 37
Michael Benjamin Avatar answered Oct 24 '22 07:10

Michael Benjamin