The example below defines a named @container
rule, and displays the properties of the associated CSSContainerRule
. The CSS is very similar to that in the @container
example Creating named container contexts.
<div id="log">
<h2>Log</h2>
<ul></ul>
<hr />
</div>
// Store reference to log list
const logList = document.querySelector("#log ul");
// Function to log data from underlying source
function log(result) {
const listItem = document.createElement("li");
listItem.textContent = result;
logList.appendChild(listItem);
}
First we define the HTML for a card
(<div>
) contained within a post
.
<div class="post">
<div class="card">
<h2>Card title</h2>
<p>Card content</p>
</div>
</div>
The CSS for the container element specifies the type of the container, and may also specify a name. The card has a default font size, which is overridden for the @container
named sidebar
if the width is greater than 700px.
<style id="example-styles">
.post {
container-type: inline-size;
container-name: sidebar;
}
/* Default heading styles for the card title */
.card h2 {
font-size: 1em;
}
@container sidebar (width >= 700px) {
.card {
font-size: 2em;
}
}
</style>
The code below gets the HTMLStyleElement
associated with the example using its id
, and then uses its sheet
property to get the StyleSheet
. From the StyleSheet
we get the set of cssRules
added to the sheet. Since we added the @container
as the third rule above, we can access the associated CSSContainerRule
using the third entry (index "2"), in the cssRules
. Last of all, we log the container name and query properties (the code that does the logging is not shown).
const exampleStylesheet = document.getElementById("example-styles").sheet;
const exampleRules = exampleStylesheet.cssRules;
const containerRule = exampleRules[2]; // a CSSContainerRule representing the container rule.
log(`CSSContainerRule.containerName: "${containerRule.containerName}"`);
The example output is shown below. The log section lists the container name string. The title in the card section should double in size as the width of the page goes over 700px.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4