How do I vertically center text with CSS?

How do I vertically center text with CSS?

To vertically center text with CSS, there are a few different approaches you can use depending on the layout and structure of your HTML elements.

  1. Using Flexbox: One of the easiest and most common methods is to use Flexbox, which allows you to align items vertically and horizontally within a container. You can achieve this by setting the display property of the container to "flex" and using the align-items and justify-content properties to center the text. For example:

    .container { display: flex; align-items: center; justify-content: center; }

    This will center the text both vertically and horizontally within the container.

  2. Using Line-Height: Another simple method is to use the line-height property. You can set the line-height property of the container to be the same as the height of the container, which will center the text vertically. For example:

    .container { height: 100px; line-height: 100px; }

    This will center the text vertically within the container with a height of 100 pixels.

  3. Using Table Display: You can also use the table display properties to vertically center text. Set the display property of the container to "table", and the display property of the child element to "table-cell". Then, set the vertical-align property of the child element to "middle". For example:

    .container { display: table; } .container p { display: table-cell; vertical-align: middle; }

    This will center the text vertically within the container using a table layout.

These are just a few of the ways to vertically center text with CSS. The approach you choose will depend on the structure and layout of your HTML elements.



Back to The Programmer Blog