kyle_figueroa kyle_figueroa - 2 months ago 7
CSS Question

How can I center text in a div with viewport units?

When using pixel units, I can align text no problem. But with viewport units, I can't get anywhere. Here is my code.



#aboutMeTitle {
height: 10vh;
background-color: #BEA69B;
display: block;
}
#aboutMeTitle p {
display: inline-block;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif, "FontAwesome Regular";
text-transform: uppercase;
letter-spacing: 0.2em;
vertical-align: middle;
text-align: center;
}

<div class="row" id="aboutMeTitle">
<p>About Me</p>
</div>




Answer

Very simple with CSS flexbox:

#aboutMeTitle {
  display: flex;
  justify-content: center;  /* center p horizontally */
  align-items: center;      /* center p vertically */
  height: 10vh;
  background-color: #BEA69B;
}
#aboutMeTitle p {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  letter-spacing: 0.2em;
}
<div class="row" id="aboutMeTitle">
  <p>About Me</p>
 </div>

Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, use Autoprefixer. More details in this answer.

Comments