Align text to center of div

I have a div about 200px x 40px in size. Sometimes this block will contain one line of text, and in other cases it will contain two lines. In case it contains 2 lines of text, I adjusted the height of the line so that it looked balanced inside the div. However, if there is one line of text, the text is aligned at the top of the div, leaving the bottom empty.

Instead, I want one line of text to be displayed vertically in the center of the div. What is the best way to fix this? Should I put text inside a secondary element, like <p> , and then try to apply vertical-align: middle ? There seems to be a simpler, more streamlined way to achieve this. Any ideas?

+4
source share
2 answers

I'm not sure if it works in any browser (works in Firefox, Chrome, IE8) (doesn't work on IE7 -)

 <div style="display: table-row; height: 180px; width: 500px;"> <div style="display: table-cell; vertical-align: middle; width: 500px; text-align: center;">Text</div> </div> 

The only solution I know that definitely works in any browser is to create a table and apply vertical cell alignment.

+9
source

Although this seems to be a simple problem, there is no simple solution for it in CSS2 AFAK. The Forrest topic provides a good overview of the various approaches to this problem.

+2
source

Source: https://habr.com/ru/post/1314004/


All Articles