CSSContainerRule: containerName property
Baseline 2023
Newly available
Since February 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
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;
}
}
Value
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 (""
).
Examples
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="example-styles">
.post {
container-type: inline-size;
container-name: sidebar;
}
/* Default heading styles for the card title */
.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("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.
Specifications
Specification |
---|
CSS Conditional Rules Module Level 5 # dom-csscontainerrule-containername |
Browser compatibility
BCD tables only load in the browser
See also
- CSS
container
shorthand property - CSS containment module
- Container queries
- Using container size and style queries