Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. CSSStyleProperties

CSSStyleProperties

TheCSSStyleProperties interface of theCSS Object Model (CSSOM) represents inline or computed styles available on an element, or the styles associated with a CSS style rule.

CSSStyleDeclaration CSSStyleProperties

Instance properties

This interface also inherits properties of its parent,CSSStyleDeclaration.

Named properties

Dash-named and camel-case-named properties for all CSS properties supported by the browser.

CSSStyleProperties.cssFloat

Special alias for thefloat CSS property.

Instance methods

This interface inherits the methods of its parent,CSSStyleDeclaration.

Description

An object of this type has dash-named properties forallCSS properties supported by the browser, including bothshorthand and longhand properties, and those with-moz and-webkit prefixes.These can accessed using methods inherited from theCSSStyleDeclaration base class, such asgetPropertyValue() andsetPropertyValue().

In addition, each dash-cased property has a correspondingcamel case-named property, where the name is generated by removing the dashes and capitalizing each word after the first one.This allows you to, for example, access themargin-top CSS property using the syntaxstyle.marginTop (wherestyle is aCSSStyleProperties), instead of the more cumbersomestyle.getPropertyValue("margin-top") orstyle["margin-top"].The CSS propertyfloat, being a reserved JavaScript keyword, is represented by thecssFloat property.

Shorthand CSS properties of the element are expanded to their corresponding long-form properties.For example, an element with style"border-top: 1px solid black" would be represented in the returned object by properties with the namesborder-top andborderTop, and the corresponding longhand propertiesborder-top-color andborderTopColor,border-top-style andborderTopStyle, andborder-top-width andborderTopWidth.

Properties and attributes with no defined value default to the empty string ("").For an object representing an inline style declaration (not computed styles) this will be any style that is not defined in the declaration block.

CSSStyleProperties object instances are exposed using the following APIs:

Examples

Basic usage

This example demonstrates how to get and set local and computed element styles using both camel case and dash-named properties.

HTML

The HTML defines a<div> with a number of styles set, nested within another that sets thefont-weight asbold.

html
<div>  <div>    Div content.    <br />    Inner: "border-top: 3px solid blue; color: red;margin:5px;".    <br />    Outer: "font-weight: bold;"  </div></div>
<pre></pre>
#log {  height: 140px;  overflow: scroll;  padding: 0.5rem;  border: 1px solid black;}

JavaScript

const logElement = document.querySelector("#log");function log(text) {  logElement.innerText = `${logElement.innerText}${text}\n`;  logElement.scrollTop = logElement.scrollHeight;}

First get the local and computed style for the element with the ID of"elt".

js
const element = document.querySelector("#elt");const elementStyle = element.style;const computedStyle = window.getComputedStyle(element);

Then we get theborderTop shorthand property of theCSSStyleProperties using the dot notation for both local and computed styles.Using the dot notation with a camel case property is the easiest way to access any property.

js
// Get style using dot notationconst elemBorderTop = elementStyle.borderTop;const compBorderTop = computedStyle.borderTop;log('Format: Style = "Element" / "Computed"');log(`"borderTop" = "${elemBorderTop}" / "${compBorderTop}"'`);

We can also get the same property using thegetPropertyValue() method or bracket notation.

js
// Get style using dashed-name property valueconst elemBorderTop = elementStyle.getPropertyValue("border-top");const compBorderTop = computedStyle.getPropertyValue("border-top");log(`"border-top" = "${elemBorderTop}" / "${compBorderTop}"'`);

The following code gets each of the longhand properties that correspond to the shorthand propertyborder-top, using the dot notation for simplicity.

js
// Get shorthand properties using dot notationconst elemBorderTopWidth = elementStyle.borderTopWidth;const compBorderTopWidth = computedStyle.borderTopWidth;log(`"borderTopWidth" = "${elemBorderTopWidth}" / "${compBorderTopWidth}"'`);const elemBorderTopColor = elementStyle.borderTopColor;const compBorderTopColor = computedStyle.borderTopColor;log(`"borderTopColor" = "${elemBorderTopColor}" / "${compBorderTopColor}"'`);const elemBorderTopStyle = elementStyle.borderTopStyle;const compBorderTopStyle = computedStyle.borderTopStyle;log(`"borderTopStyle" = "${elemBorderTopStyle}" / "${compBorderTopStyle}"'`);const elemFontWeight = elementStyle.fontWeight;const compFontWeight = computedStyle.fontWeight;log(`"fontWeight" = "${elemFontWeight}" / "${compFontWeight}"'`);

Lastly we demonstrate how you can use the dot notation to set a property value.In the following results section you will note that the bottom border of the element is a solid green line.

js
// Set the bottom border style using dot notationelementStyle.borderBottom = "5px solid green";

Results

The results are shown below.Note how the values from the corresponding camel case (borderTop) and dash-named (border-top) properties are the same.The local and computed values for the longhand properties are often the same too, except that computed properties usergb() syntax for colors and additionally include styles set on the parent<div>, such as thefont-weight.

Enumerate dash-named style properties

This example demonstrates how to enumerate the dash-named property values of an element, for both the inline and computed style.

HTML

The HTML defines a<div> with a number of styles set, nested within another that sets thefont-weight.There are also buttons to get the inline styles and computed styles for the element (and hidden code for a reset button and logging).

html
<div>  <div>    An example div  </div></div><button type="button">Inline Style</button><button type="button">Computed Style</button>
<button type="button">Reset</button><pre></pre>
#log {  height: 300px;  overflow: scroll;  padding: 0.5rem;  border: 1px solid black;}
const logElement = document.querySelector("#log");function log(text) {  logElement.innerText = `${logElement.innerText}${text}\n`;  logElement.scrollTop = logElement.scrollHeight;}function clearLog(text) {  logElement.innerText = "";}const reload = document.querySelector("#reset");reload.addEventListener("click", () => {  clearLog();});

JavaScript

The code first defines the function we're going to use to enumerate the properties of our element with theelt ID.This usesCSSStyleDeclaration.getPropertyValue() to get the value of each dash-named property owned by the object that has a numeric index.

js
function getPopulatedProperties(elementStyles) {  for (const prop in elementStyles) {    if (      // Check the property belongs to the CSSStyleProperties instance      // Check property has a numeric index (indicates inline/dash-named style)      Object.hasOwn(elementStyles, prop) &&      !Number.isNaN(Number.parseInt(prop, 10))    ) {      log(        `${elementStyles[prop]} = '${elementStyles.getPropertyValue(          elementStyles[prop],        )}'`,      );    }  }}

The following code checks and logs whetherCSSStyleProperties is defined.If it exists then we create button event handlers to get the inline or computed styles for the element and log their names and values.

js
if (typeof window.CSSStyleProperties === "undefined") {  log("CSSStyleProperties is not supported on this browser.");} else {  const element = document.querySelector("#elt");  const inlineStyle = document.querySelector("#inline_style");  inlineStyle.addEventListener("click", () => {    clearLog();    const elementStyle = element.style;    getPopulatedProperties(elementStyle);  });  const computedStyle = document.querySelector("#computed_style");  computedStyle.addEventListener("click", () => {    clearLog();    const compStyles = window.getComputedStyle(element);    getPopulatedProperties(compStyles);  });}

Results

Press the buttons to show the dash-named property names and values for the element's inline and computed styles.Note that the inline styles only include the styles defined on the actual element: all the other properties have the value"" and are not displayed.The computed styles also includefont-weight, which is defined on the parent, and many other computed styles.

Specifications

Specification
CSS Object Model (CSSOM)
# cssstyleproperties

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp