How do I vertically center text with CSS?

 

To vertically center text within an HTML element using CSS, you can use a combination of CSS flexbox or CSS Grid. Here's an example using both methods:

HTML:

html
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <div class="container flexbox"> <p>Vertically Centered Text (Flexbox)</p> </div> <div class="container grid"> <p>Vertically Centered Text (CSS Grid)</p> </div> </body> </html>

CSS (styles.css):

css
body { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; } .container { width: 300px; height: 100px; border: 1px solid #ccc; text-align: center; font-size: 18px; } /* Using Flexbox */ .flexbox { display: flex; align-items: center; justify-content: center; } /* Using CSS Grid */ .grid { display: grid; place-items: center; }

In this example:

  1. We have an HTML file that includes two div containers with text and CSS classes flexbox and grid.

  2. In the CSS (styles.css) file, we apply styles to vertically center the text within these containers.

  3. We use the display: flex; property on the body element to make it a flex container.

  4. We set align-items: center; and justify-content: center; on the body element to center its children both vertically and horizontally.

  5. Inside the .container class, we set the width, height, and other styles as desired.

  6. For the container with the flexbox class, we use display: flex;, align-items: center;, and justify-content: center; to vertically and horizontally center the text using flexbox.

  7. For the container with the grid class, we use display: grid; and place-items: center; to center the text using CSS Grid.

When you open the HTML file in a web browser, you will see two containers with text that are vertically centered on the page using both flexbox and CSS Grid techniques.

Comments