Recipe 12.4

Creating a Profile Card Component

Demo

Phillip Chavez
CEO

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor. Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius pharetra.

Jamie Lynch
Vice President

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor. Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius pharetra.

Code

JavaScript
const template = document.createElement('template');
template.innerHTML = `
  <style>
    :host {
      display: grid;
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 8px;
      grid-template-columns: auto 1fr;
      column-gap: 16px;
      align-items: center;
      margin: 1rem;
    }

    .photo {
      border-radius: 50%;
      grid-row: 1 / span 3;
    }

    .name {
      font-size: 2rem;
      font-weight: bold;
    }

    .title {
      font-weight: bold;
    }
  </style>

  <div class="photo"><slot name="photo"></slot></div>
  <div class="name"><slot name="name"></slot></div>
  <div class="title"><slot name="title"></slot></div>
  <div class="bio"><slot></slot></div>
`;

class ProfileCard extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

if (!customElements.get('profile-card')) {
  customElements.define('profile-card', ProfileCard);
}
HTML
<profile-card>
  <img slot="photo" src="/user.png" />
  <div slot="name">Phillip Chavez</div>
  <div slot="title">CEO</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor.
    Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis
    lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius
    pharetra.
  </p>
</profile-card>

<profile-card>
  <img slot="photo" src="/user.png" />
  <div slot="name">Jamie Lynch</div>
  <div slot="title">Vice President</div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc in porta justo. Duis bibendum iaculis auctor.
    Vestibulum ut elit in lacus congue vehicula. Aliquam laoreet varius ipsum sit amet iaculis. Cras fringilla mattis
    lacinia. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed blandit varius
    pharetra.
  </p>
</profile-card>
Web API Cookbook
Joe Attardi