files/en-us/web/api/csspagerule/index.md
{{APIRef("CSSOM")}}
CSSPageRule represents a single CSS {{cssxref("@page")}} rule.
{{InheritanceDiagram}}
Inherits properties from its ancestors {{domxref("CSSGroupingRule")}} and {{domxref("CSSRule")}}.
Inherits methods from its ancestors {{domxref("CSSGroupingRule")}} and {{domxref("CSSRule")}}.
This example shows how you can find CSSPageRule objects for {{cssxref("@page")}} rules loaded by the document.
<pre id="log"></pre>
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
#log {
height: 220px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
Below we define styles for the page using a {{cssxref("@page")}} rule.
@page {
margin: 1cm;
}
The code iterates through all the sheets in the document, and through all the cssRules in each sheet, logging the sheet index, the number of rules, and the type of each rule object.
We then detect CSSPageRule objects using their type (doing nothing with the information).
for (
let sheetCount = 0;
sheetCount < document.styleSheets.length;
sheetCount++
) {
const sheet = document.styleSheets[sheetCount].cssRules;
log(`styleSheet: ${sheetCount}`);
const myRules = document.styleSheets[sheetCount].cssRules;
log(`rules: ${myRules.length}`);
for (const rule of myRules) {
log(`rule: ${rule}`);
if (rule instanceof CSSPageRule) {
// Do something with CSSPageRule
}
}
}
The results are shown below.
As you can see there are a two sheets, corresponding to this main document and the example code frame, and each have a number of rules, only one of which is our CSSPageRule.
{{EmbedLiveSample("Filtering for page rules", "100%", "300px")}}
{{Specifications}}
{{Compat}}