Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I vertically center text? [duplicate]

Tags:

html

css

I've been working on getting the text in my content div centered vertically and I'm stumped. The container includes 1 div with a title and 1 div with content.

I've tried elements such as:

vertical-align: middle;

and also playing with the displays/positioning, but I'm not having any luck.

The current CSS is the following:

.content-wrapper {
  height: 100vh;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: left;
  text-align: left;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  color: #000;
  font-family: Montserrat;
  text-transform: none;
  -webkit-transform: translateY(40vh);
  transform: translateY(40vh);
  will-change: transform;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
  transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
  padding-top: 10%;
  padding-right: 25px;
  padding-left: 30px;
  float: right;
  width: 35%;
  background-color: #f0f7fc;
}
like image 663
Petey Avatar asked May 05 '17 14:05

Petey


1 Answers

Flexbox

Flexbox allows you to vertically align the text without having a div with a fixed height. It is now supported by all the modern browsers.

Check my other answer to see all the problems and workarounds for Flexbox. The majority are for Internet Explorer.

display: flex;
align-items: center;

div {
  width: 50px;
  height: 100px;
  display: flex;
  align-items: center;
  border: 1px solid black;
}
<div>
  Test
</div>

line-height

If you know the height of the external div, you can use line-height.

height: 100px;
line-height: 100px; /* same value as height */

div {
  width: 50px;
  height: 100px;
  line-height: 100px;
  border: 1px solid black;
}
<div>
  Test
</div>

display: table-cell

display: table-cell is another good alternative which allows you to vertically align without knowing the height of the div. It works in older browsers too (except Internet Explorer 7).

display: table-cell;
vertical-align: middle;

div {
  width: 50px;
  height: 100px;
  display: table-cell;
  vertical-align: middle;
  border: 1px solid black;
}
<div>
  Test
</div>
like image 172
Paolo Forgia Avatar answered Sep 29 '22 10:09

Paolo Forgia