A CSS selector is a pattern that identifies elements for styling. Broad selectors such as button can unintentionally match unrelated content, while component-qualified selectors narrow the match and limit style creep. section 9.1
Selectors become especially important when styles meet Web Components:
- Qualify common elements, such as sample-component button, when styles live in the page’s global style space. section 9.1
- Inside a Shadow DOM, generic selectors such as button and span can safely target internal elements because the DOM is separate. section 9.2
- Use :host to style the custom element that contains the shadow root; a selector for the host does not style the shadow contents. section 9.2
A selector for a stepper
A global button rule can restyle a stepper’s plus and minus buttons. Replacing it with sample-component button.big-button narrows the rule to the intended controls. Moving the controls into a Shadow DOM then allows internal button rules without the same page-level collisions. section 9.1 section 9.2
Listing 9.1. A stepper component without logic, just style
<html>
<head>
<script>
class SampleComponent extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<button class="big-button">-</button> #1
<span class="increment-number">5</span> #2
<button class="big-button">+</button> #3
<style> #4
sample-component {
display: flex;
}
sample-component .increment-number {
font-size: 24px;
background-color: #770311;
color: white;
font-family: Helvetica;
display: inline-block;
padding: 11px;
border: none;
}
sample-component button { #5
border-radius: 0 50px 50px 0;
border: none;
width: 50px;
height: 50px;
font-size: 36px;
font-weight: bold;
background-color: red;
color: white;
}
sample-component button:first-child {
border-radius: 50px 0 0 50px;
}
sample-component .big-button:active {
background-color: #960000;
}
sample-component .big-button:focus {
outline: thin dotted;
}
</style>`;
}
}
if (!customElements.get('sample-component')) {
customElements.define('sample-component', SampleComponent);
}
</script>
</head>
<body>
<sample-component></sample-component> #6
</body>
</html>
Inspect the stepper markup and its progressively qualified selectors. section 9.1







