4

How do I center text vertically and horizontally to the center of the page?

For example, if I have this text, "Enter the codes".

Also, bonus related question, does it matter if it's text or an image? I ask because I may put an image to the left of the text.

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

1 Answers1

0

I'm not exactly sure what you mean by "center" (there are several definitions), but perhaps this will do what you want:

<div class="myclass">Some text</div>

.myclass {
    position: absolute;
    left: 50%;
    top: 50%;
}

It doesn't matter if it's text or an image - the browser just regards it as block content.

Note that text-align: center; will center items horizontally within their container.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 4
    For what it's worth, this would not "center" an image, it would align the left and top corners to the center point of the body, not the center of the image, which is what would likely be desired. – FilmJ Sep 21 '12 at 21:22
  • 4
    To center the element, pair this with a transform: `transform: translateX(-50%) translateY(-50%);` (with prefixes if needed) – Zach Saucier Oct 24 '15 at 20:32
  • What other definitions for center are there beyond "place in the middle"? – DavidB Apr 21 '17 at 13:31
  • "Align the left edge of this text to the pixel halfway between the left and right edges of the screen". " Place this text so that exactly half of its pixels lie on the left half of the screen, and half of its pixels lie on the right". "Place this text so that half of its characters lie on the left half of the screen". These three definitions all produce different results. – Borealid Apr 21 '17 at 20:03
  • If you want text to be truly at the center (taking the length of the text into account) then the class should be: .text { position: absolute; text-align: center; top: 50%; width: 100%; } – Varun Sharma Feb 10 '21 at 19:48