Forum How do I...?

... put text in the middle of a page?

erelsgl
I tried:
  page-break-before: always; 
  page-break-after:  always; 
  vertical-align: center;
  margin: auto;


but the text appeared at the top-left part of the page.
mikeday
The vertical-align property specifies the alignment of text relative to surrounding text and the alignment of table cell content; it cannot be used to vertically align an entire block.

One way to vertically center a block on the page is to make it absolutely positioned, with margin-top and margin-bottom of auto. However, for this to work you also need to specify a non-auto value for "top", "bottom" and "height":

<html>
<head>
<style>
@page {
    border: solid cyan 1px
}
#foo {
    position: absolute;
    margin: auto;
    text-align: center;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 3cm;
    border: solid red thin;
}
</style>
</head>
<body>
    <div id="foo">Hello, world!</div>
</body>
</html>

There does not appear to be any way in CSS to vertically center a block with an automatically determined height. However, I believe that the CSS working group is considering adding "position: center" or some other property for this purpose.
erelsgl
Thanks, this works if this div foo is the only content in the document. However, if there is more content before or after foo, then foo is printed on top of them, and not in a seperate page (the page-break-before and page-break-after are ignored...)

What I wanted to do is, put every h2 heading in a seperate page, to create a nice opening page to each chapter.

Currently I use an approximate solution - since the height of the heading text is no more than 9cm, I put 10cm margins on top and bottom, so it is positioned approximately in the middle:

  position: static;  
  margin: 10cm auto 10cm auto;
mikeday
You will need a separate wrapper element to specify the page break properties on, as they do not affect positioned elements:
div {
    page-break-before: always;
    page-break-after: always;
}

h2 {
    position: absolute;
    ...
}

<div>
<h2>Chapter title</h2>
</div>