part

The HTML part attribute allows for the identification of distinct sections within a web component, facilitating targeted styling and scripting for various parts of custom elements.

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

index.html
<element part="name">Content</element>

Example

::atter-part ::
<!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>

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.