How do I vertically align text in a div, please provide sample?
How do I vertically align text in a div, please provide sample?
16031-Jul-2023
Updated on 01-Aug-2023
Home / DeveloperSection / Forums / How do I vertically align text in a div, please provide sample?
How do I vertically align text in a div, please provide sample?
Aryan Kumar
01-Aug-2023There are a few ways to vertically align text in a div. Here are a few methods:
Using CSS
The simplest way to vertically align text is to use CSS. You can add the following CSS rule to your HTML document:
CSS
This will vertically align the text in the div to the middle of the div.
Using JavaScript
You can also vertically align text using JavaScript. The following JavaScript code will vertically align the text in the div to the middle of the div:
JavaScript
This code will first get the height of the div and the height of the text in the div. Then, it will calculate the top position of the text in the div and set the
top
property of the div to the calculated value.Using Flexbox
You can also vertically align text using Flexbox. Flexbox is a CSS layout system that allows you to easily control the layout of elements on a page. To vertically align text using Flexbox, you can add the following CSS code to your HTML document:
CSS
This will vertically align the text in the div to the center of the div.
Here is an example of how to vertically align text in a div using CSS:
HTML
This code will create a div with the text "This is some text". The text will be vertically aligned to the middle of the div.