> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/css/properties/get-set-css-props.md).

# get/set CSS props

{% hint style="warning" %}
⭐️ 注意：

不要將 **Element**.[**getAttribute**](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute)()、**CSSStyleDeclaration**.[**getPropertyValue**](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue)() 與 **Element**.[**setAttribute**](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute)()、**CSSStyleDeclaration**.[**setProperty**](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty)()搞混了❗️
{% endhint %}

{% tabs %}
{% tab title="小抄" %}

```javascript
// get: 
elem.style.color                // 使用 <elem style="...">
getComputedStyle(elem).color    // ⭐️ computed style ≠ elem.style.color❗️

// set: 
elem.style.color = 'pink';           // 設定內建樣式
elem.styleProp('--css-var', '4px');  // 設定自訂 css var
```

{% endtab %}

{% tab title="詳解" %}

```javascript
// get
// ⭐️ 注意：`elem.style` 只存取來自 <... style="..."> 的樣式, 通常為 ''❗️ 
elem.style.backgroundColor    
elem.style.getPropertyValue('margin-top')  // ⭐️ = elem.style.marginTop

// ⭐️ computed style (read-only❗️)
//    此處為「套用所有樣式」後所得到的結果，所以一定有值。
getComputedStyle(elem).color  

// set
elem.style.display = "none"
style.setProperty('margin-top', '4px')    // ⭐️ style.marginTop = '4px'
```

{% endtab %}

{% tab title="⬆️ 需要" %}

* Element ⟩ [.styleProp()](/web/browser/dom/type/element/+ext/.styleprop.md)

{% endtab %}

{% tab title="📘 手冊" %}

* MDN ⟩&#x20;
  * CSSStyleDeclaration ⟩ .[setProperty](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty)(), .[getPropertyValue](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue)()
  * Window ⟩ .[getComputedStyle](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)()
    {% endtab %}

{% tab title="👥 相關" %}

* [⭐️ Fav](/web/master/fav.md)
  {% endtab %}
  {% endtabs %}

{% tabs %}
{% tab title="📗 參考" %}

* W3School ⟩ [CSS Default Values Reference](https://www.w3schools.com/cssref/css_default_values.asp)
* JS.info ⟩ [Styles and classes](https://javascript.info/styles-and-classes)
  {% endtab %}

{% tab title="📘 手冊" %}

* W3C ⟩ [Full Property List](https://www.w3.org/TR/CSS2/propidx.html)
  {% endtab %}

{% tab title="👥 相關" %}

* [HTML Attributes vs. DOM Properties](/web/browser/dom/type/element/attribute/attrs-vs-props.md)
* Element ⟩ [.styleProp()](/web/browser/dom/type/element/+ext/.styleprop.md)
  {% endtab %}
  {% endtabs %}

## CSS vs. DOM style prop names <a href="#css-vs-dom-prop-names" id="css-vs-dom-prop-names"></a>

| CSS prop (kebab case) | DOM prop (camel case)          |
| --------------------- | ------------------------------ |
| 'background-color'    | elem.style.**backgroundColor** |
| 'z-index'             | elem.style.**zIndex**          |
| 'border-left-width'   | elem.style.**borderLeftWidth** |

## code example <a href="#example" id="example"></a>

{% hint style="danger" %}
The **style** *property* operates only on the value of the "**style**" *attribute*, **without** any CSS cascade. 👉🏻 See "**elem.style**" tab below.
{% endhint %}

{% tabs %}
{% tab title="example" %}

```javascript
const {log} = console;

const p1 = $('p:nth-of-type(1)');
const p2 = $('p:nth-of-type(2)');

// css properties (kebab case)
const cssProps = [
  'background', 'color', 'background-color', 'border',
  'border-radius', 'padding', 'padding-left',
];

// DOM style properties (camel case, e.g. 'paddingLeft')
const styleProps = cssProps.map(prop => prop.kebabToCamelCase());

/*
  ⭐️ The `style` property operates only on the value of 
     the "style" attribute, WITHOUT any CSS cascade❗️
*/

//             ╭──elem.style──╮ ╭───────────── style.getPropertyValue() ────────────╮
// css prop   | p1         p2  |  p1                       | p2
// -----------------------------------------------------------------------------------
// background | yellow     ''  | rgb(255, 255, 0) none ... | rgba(0, 0, 0, 0) none ...
// color      | red        ''  | rgb(255, 0, 0)            | rgb(0, 0, 0)
// bg-color   | yellow ⭐️  ''  | rgb(255, 255, 0)          | rgba(0, 0, 0, 0)
// border     | ''         ''  | 1px solid rgb(0, 0, 0)    | same
// border-rad | ''         ''  | 4px                       | same
// padding    | ''         ''  | 0px 16px                  | same
// padding-l  | ''         ''  | 16px                      | same

// show elem.style
function showStyles2(elem){
  styleProps                              // color, border, ...
    .map(prop => elem.style[prop])        // style.color, style.border, ...
    .forEach(x => log(x));
}

// get computed styles
function showStyles3(elem){
  cssProps                                // border-radius, padding-left
    .map(prop => elem.styleProp(prop))    // getPropertyValue('border-radius'), ...
    .forEach(x => log(x));
}

showStyles2(p1);
showStyles2(p2);

showStyles3(p1);
showStyles3(p2);

// before set
log(p1.styleProp('padding-left'));      // 16px
log(p1.styleProp('paddingTop'));        // 0px
log(p1.style.paddingLeft);              // ''   ⭐️
log(p1.style.paddingTop);               // ''   ⭐️

// set
p1.style.paddingLeft = '100px'; 
p1.styleProp('padding-top', '30px');

// after set
log(p1.styleProp('padding-left'));      // 100px
log(p1.styleProp('paddingTop'));        // 30px

log(p1.style.paddingLeft);              // 100px
log(p1.style.paddingTop);               // 30px
```

{% endtab %}

{% tab title="CSS" %}

```css
body {
  background: #aaa;
}

p {
  border: 1px solid black;
  border-radius: 4px;
  padding: 0 1em;
}
```

{% endtab %}

{% tab title="HTML" %}

```markup
<p style="background: yellow; color: red;">this is a paragraph</p>
<p>this is another paragraph.</p>
```

{% endtab %}

{% tab title="⬆️ 需要" %}

* [$(), $all()](/web/browser/dom/querying-elements/dom.md)
* String ⟩ [.capitalize()](/web/js/val/prim/str/method/.capitalize.md), [.kebabToCamelCase()](/web/js/val/prim/str/method/.kebabtocamelcase.md)
* Element ⟩ [.styleProp()](/web/browser/dom/type/element/+ext/.styleprop.md)
  {% endtab %}

{% tab title="💾 程式" %}

* codepen ⟩ [elem.style](https://codepen.io/lochiwei/pen/mdwNEgK?editors=0011)
* replit ⟩ [style.setProperty()](https://replit.com/@pegasusroe/stylesetProperty#script.js) - set border, backgroundColor, color randomly.
  {% endtab %}
  {% endtabs %}
