The read-only containerName
property of the CSSContainerRule
interface represents the container name of the associated CSS @container
at-rule.
For example, the value of containerName
for the @container
below is sidebar
:
@container sidebar (min-width: 700px) {
.card {
font-size: 2em;
}
}
A string that contains the container-name
of the @container
associated with this CSSContainerRule
. If the @container
is not named, the function returns the empty string (""
).
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.
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 minimum width is greater than 700px.
<style id="examplestyles">
.post {
container-type: inline-size;
container-name: sidebar;
}
.card h2 {
font-size: 1em;
}
@container sidebar (min-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("examplestyles").sheet;
const exampleRules = exampleStylesheet.cssRules;
const containerRule = exampleRules[2];
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.