Gorg Gorg - 2 months ago 9
CSS Question

vertically align text within itself

I have an

h3
with a height of
100%
. Therefore the height is unknown. How can I center the text within itself? For the sake of the example, I have given the parent fixed dimensions but this is not the case. I have tried using vertical align but that doesn't work, I believe I may need to change the
display
to do that?

I don't want to center the text within its parent, I want to know if it is possible to center it within itself. The text needs to be 100% in both dimensions so that the fills the parent div.



.unknowndimensions{
height:300px;
width:300px;
}
.unknowndimensions h3{
height:100%;
width:100%;
background:#f7f700;
text-align:center;
}

<div class="unknowndimensions">
<a href="#"><h3>Title</h3></a>
</div>




Answer

You can make your .unknowndimensions element a flex-container. You then use justify-content: center and align-items: center to center both horizontally and vertically, respectively.

body {
  margin: 0;
}
.unknowndimensions {
  height: 100vh;
  background-color: dodgerblue;
  display: flex;
  justify-content: center;
  align-items: center;
}
.unknowndimensions h3 {
  margin: 0;
  background: #f7f700;
}
<div class="unknowndimensions">
  <a href="#"><h3>Title</h3></a>
</div>


More Info:

You can find more info and resources in this post.