part
part Attribute
The part
attribute enables elements inside a Shadow DOM to be styled from outside. It marks specific parts within a shadow tree that can be targeted by external CSS.
Purpose
The part
attribute designates particular sections of an element for external styling, making it particularly useful with Shadow DOM components.
Syntax
<element part="name">Content</element>
Example
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
h1 {
color: green;
}
tabbed-custom-element::part(tab) {
color: green;
border-bottom: dotted 2px;
width: 400px;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<strong>HTML part Attribute</strong>
<br><br>
<template id="tabbed-custom-element">
<div part="tab">Hypertext Markup Language</div>
<div part="tab active">Cascading Style Sheet</div>
<div part="tab">JavaScript</div>
</template>
<tabbed-custom-element></tabbed-custom-element>
</center>
</body>
</html>
// Using the selector to select the
// part attributes elements
let template = document
.querySelector("#tabbed-custom-element");
globalThis.customElements.define(
template.id, class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content);
}
});
Usage
- Definition: Assigns names to specific parts of an element to enable targeted styling.
- Application: Frequently used in web components to apply external styles.
Key Points
- Allows external styles to target internal elements within a custom element using Shadow DOM.
- Supports multiple part names, separated by spaces.
- Utilizes the
::part()
CSS pseudo-element for styling.
Conclusion
The part
attribute in HTML allows specific parts of an element inside a Shadow DOM to be styled from outside, facilitating better control over web components. It is particularly useful for targeting sections of custom elements for styling without exposing the entire structure. This attribute works in conjunction with the ::part()
CSS pseudo-element for external styling.
nonce
The HTML nonce attribute provides a unique token for <script> or <style> elements, enhancing security by allowing only authorized content to be executed or applied.
ping
The HTML ping attribute designates URLs that will be notified when a user clicks a link, enabling tracking without affecting the user's browsing experience.