Printing text in html in the center of the page
I have a next question-tried to find it with google, but didn't find what could help me. I have a big HTML file that I need to print, to separate pages I use CSS break-after
.
The quesion is: how can I print an element in the center of the page, not only horizontal center but vertical too. The HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<style>
@media all {
body
{
text-align:left;
}
p.paragrpahs
{
text-align:center;
font-family:Arial,Helvetica,sans-serif;
font-size:32px;
font-weight:bold;
vertical-align: center;
}
.break_here
{
page-break-before:always;
}
}
</style>
</head>
<body>
*Tons of text*
<p class="break_here"><p class="paragrpahs">Some text</p><p class="break_here">
*Tons of text*
</body>
</html>
Solution 1:
First of all, it is vertical-align: middle
, not vertical-align: center
, see MDN - vertical-align.
There's a nice article about centering at CSS Tricks - Centering in the Unknown. Transfering this to your example, you must first set
html, body {
height: 100%;
}
and
p.paragrpahs {
height: 100%;
}
and then add the mentioned "ghost" element
p.paragrpahs:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
This will give you a vertically centered text on a whole page, see JSFiddle. When you use p.paragrpahs
(sic?) for other things as well, you should add a separate vcenter
class or similar, of course.
Update:
With longer text (more than one line), this doesn't work, unfortunately. If you have longer text, you can wrap the text into a span
element
<p class="paragrpahs"><span>Lorem ipsum dolor sit amet, ...</span></p>
and give this a
p.paragrpahs span {
display: inline-block;
}
Then this inline-block
span
will again vertically align with the ghost (:before
) element.
See updated JSFiddle.