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 div
s 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>
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With