Frontend developer using browser DevTools to investigate inherited text color beyond a CSS @scope limit

Why Text Keeps Its Color Beyond a CSS @scope Limit

Wed, Nov 25, 2026

A nested component can stop receiving a scoped selector’s direct declarations and still keep the outer component’s text color. That is not evidence that the lower limit failed. It is the expected consequence of two CSS mechanisms operating at different stages: @scope restricts where selectors in a scoped rule can match, while color is an inherited property whose computed value can continue from parent to child through ordinary light-DOM ancestry. Chrome’s implementation guidance describes this distinction as selector isolation rather than style isolation, including inherited color crossing a scope’s lower boundary. The CSS Cascading and Inheritance Level 6 draft separately defines elements at a scoping limit and their descendants as outside the containing scope.

The release question is therefore narrower than “does @scope work?” It is: can we demonstrate that the outer selector stops at the boundary, identify inheritance as the source of the surviving color, and change the embedded component’s color policy without widening the outer scope?

This playbook answers that question with ten independently predicted cases, S01 through S10. No browser experiments are reported as executed here. Every behavioral result is EXPECTED / NOT EXECUTED, every observed scalar remains not collected, and the runtime decision is HOLD until a complete run produces a reconcilable ledger. The proposed commissioning baseline is CPython 3.12.14, Python Playwright 1.62.0 and packaged Chromium 151.0.7922.34, browser revision 1234. Those labels identify a proposed environment only; a real run must capture the executable actually launched, browser.version(), operating system, architecture, launch options, fixture digest and accessibility-related environmental state.

The diagnostic standard is intentionally stricter than reading one color from DevTools. We separate selector eligibility, inherited values and directly specified values; use a non-inherited background marker as supporting evidence; preserve literal stylesheets and DOM shape; and require changed-one-input controls before accepting a component-boundary repair.

Define the component contract before interpreting the cascade

The fixture has three ownership regions. #shell.shell is the outer component and scoping root. #owned.probe is content that unquestionably belongs to that component. #boundary.embedded.probe, containing #inner.probe, represents an embedded component at the lower scope boundary. #outside.probe sits outside the shell and checks that the experiment does not leak beyond the intended root.

The product contract must precede observation:

Region

Required color policy

Meaning

#owned

rgb(125, 45, 120)

Outer component owns this text color.

#boundary

rgb(20, 90, 110)

Embedded component owns a distinct local color.

#inner

rgb(20, 90, 110)

Descendant inherits the embedded component policy.

#outside

rgb(30, 30, 30)

Outer scope must not affect unrelated content.

This policy matters because specification-conforming behavior can still violate the product requirement. In S03, the correct CSS mechanism is expected to produce OUTER on the excluded embedded subtree. That would support the diagnosis while failing the local component policy. Conversely, a reviewed component intentionally designed to inherit the outer theme would require no repair at all.

Do not substitute a cascade-precedence investigation for this contract. Questions involving layer ordering, competing declaration precedence and !important belong in the separate Refonte article on cascade-layer migration validation. That page is useful for delimiting the problem, not for proving @scope inheritance semantics. Its inspected experiment explicitly concerns layers rather than the inheritance-dependent output tested here.

Three evidence categories must remain distinct throughout this playbook.

Documented platform behavior comes from primary specifications and implementation guidance. The CSSWG Level 6 draft defines a scope by a scoping root and optional scoping limits, and says an element is in scope when it is an inclusive descendant of the root but not an inclusive descendant of a scoping limit. It also states that elements matched by a lower-bound selector are excluded from the resulting scope. Because this is an Editor’s Draft, treat it as work in progress rather than an immutable standard snapshot. CSS Cascading and Inheritance Level 6 supplies those definitions.

Author-designed expectations are the S01-S10 manifest below. They are predictions derived independently from the declared DOM, fixed CSS candidates and documented semantics.

Browser observations are primitive values copied by an actual recorded run. There are none yet. Package metadata and a packaged-browser manifest do not convert predictions into observations.

This separation is especially important for an inherited property. CSS Color Level 4 defines color as inherited. CSS Color Level 4 currently lists its initial value as CanvasText, applies it to all elements and text, and marks inheritance as yes. The fixture does not rely on the environment-dependent initial color because body explicitly establishes rgb(30, 30, 30).

The actual question can therefore be stated precisely:

Does the lower scope limit prevent scoped rules from selecting #boundary and #inner, while ordinary parent-to-child inheritance still supplies the color value that #shell acquired from a scoped :scope declaration?

Nothing in that question requires Shadow DOM, slots, framework style rewriting, cascade layers, animations, transitions, custom properties, containment, positioning or a security-isolation model.

Pin the disposable fixture and its expected manifest

Use a new rendered document for every case. Do not keep mutating a long-lived page across S01-S09, because stale DOM or styles would make the evidence harder to reconcile. S10 is deliberately different: its three phases occur in one fresh case document because the changing boundary class is the controlled input being tested.

The proposed Python environment can be prepared as follows. These commands install the requested package baseline; they do not prove which executable a later run actually launches.

python3.12 -m venv .venv
. .venv/bin/activate

python -m pip install --upgrade pip
python -m pip install "playwright==1.62.0"

python -m playwright install chromium

python --version
python -m pip show playwright

A release or package label verifies identity metadata, not browser behavior. If the resulting Playwright installation does not contain the proposed Chromium 151.0.7922.34 / revision 1234 combination, do not copy those numbers into the evidence. Record the mismatch as a new baseline candidate and capture what actually executes.

The fixed DOM is deliberately ordinary light DOM:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSS scope inheritance fixture</title>
  <style id="under-test">
    /* Case-specific literal stylesheet is inserted here. */
  </style>
</head>
<body>
  <div id="shell" class="shell">
    <p id="owned" class="probe">Owned text</p>

    <section id="boundary" class="embedded probe">
      Embedded boundary
      <p id="inner" class="probe">Embedded inner text</p>
    </section>
  </div>

  <p id="outside" class="probe">Outside text</p>
</body>
</html>

Readers who need prerequisite DOM, selector and stylesheet context can use Refonte’s HTML and CSS foundations; that introductory material is not an authority for the scoped-style semantics in this test.

The fixture constants become literal CSS values, never undeclared identifiers:

body {
  color: rgb(30, 30, 30);
}

/* BASE  = rgb(30, 30, 30)
   OUTER = rgb(125, 45, 120)
   INNER = rgb(20, 90, 110)
   MARK  = rgb(215, 235, 220)
   CLEAR = rgba(0, 0, 0, 0) */

#boundary is itself a .probe on purpose. A lower limit is exclusive under the scoped-style definition, so the boundary element is a first-class target for the experiment, not merely a convenient ancestor of #inner. Testing only the descendant would throw away the most direct evidence.

The independent expected-case manifest follows. “Observed” is not part of this table because expectations are authored before collection.

Case

Controlled input

Independent expected values

Expected interpretation

Status

S01

Body baseline only

owned BASE/CLEAR; boundary BASE/CLEAR; inner BASE/CLEAR; outside BASE/CLEAR

Baseline inheritance only.

EXPECTED / NOT EXECUTED

S02

@scope (.shell) with no lower limit; :scope sets OUTER; .probe sets MARK

owned OUTER/MARK; boundary OUTER/MARK; inner OUTER/MARK; outside BASE/CLEAR

Unrestricted scope reaches all probes inside shell.

EXPECTED / NOT EXECUTED

S03

Add to (.embedded)

owned OUTER/MARK; boundary OUTER/CLEAR; inner OUTER/CLEAR; outside BASE/CLEAR

Selector boundary holds; outer color still inherits; embedded product policy fails.

EXPECTED / NOT EXECUTED

S04

Keep lower limit; remove root color; scoped .probe gets OUTER and MARK

owned OUTER/MARK; boundary BASE/CLEAR; inner BASE/CLEAR; outside BASE/CLEAR

Removing shell’s color removes S03’s inherited input.

EXPECTED / NOT EXECUTED

S05

Change lower limit to .embedded > *

owned OUTER/MARK; boundary OUTER/MARK; inner OUTER/CLEAR; outside BASE/CLEAR

Boundary becomes eligible; inner becomes the limit. Color still inherits.

EXPECTED / NOT EXECUTED

S06

S03 plus .embedded { color: INNER; } inside same outer scope

owned OUTER/MARK; boundary OUTER/CLEAR; inner OUTER/CLEAR; outside BASE/CLEAR

Candidate repair cannot select the excluded boundary.

EXPECTED / NOT EXECUTED

S07

S03 plus unscoped #boundary { color: INNER; }

owned OUTER/MARK; boundary INNER/CLEAR; inner INNER/CLEAR; outside BASE/CLEAR

Explicit boundary ownership satisfies policy without widening outer selector reach.

EXPECTED / NOT EXECUTED

S08

S03 plus external #boundary { color: unset; }

owned OUTER/MARK; boundary OUTER/CLEAR; inner OUTER/CLEAR; outside BASE/CLEAR

unset preserves inheritance for inherited color; not an isolation reset.

EXPECTED / NOT EXECUTED

S09

S03 plus separate @scope (.embedded) { :scope { color: INNER; } }

owned OUTER/MARK; boundary INNER/CLEAR; inner INNER/CLEAR; outside BASE/CLEAR

Embedded component establishes its own scoped root color.

EXPECTED / NOT EXECUTED

S10

S03; remove .embedded; restore .embedded

Phase A: boundary/inner OUTER/CLEAR. Phase B: boundary/inner OUTER/MARK. Phase C: boundary/inner OUTER/CLEAR. Owned always OUTER/MARK; outside BASE/CLEAR.

Marker follows scope eligibility; inherited color remains OUTER throughout.

EXPECTED / NOT EXECUTED

The literal case stylesheets should live beside, rather than inside, the observation function. A compact Python manifest can define them independently:

BASE = "rgb(30, 30, 30)"
OUTER = "rgb(125, 45, 120)"
INNER = "rgb(20, 90, 110)"
MARK = "rgb(215, 235, 220)"
CLEAR = "rgba(0, 0, 0, 0)"

BODY = "body { color: rgb(30, 30, 30); }"

CASE_CSS = {
    "S01": BODY,
    "S02": BODY + """
@scope (.shell) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}""",
    "S03": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}""",
    "S04": BODY + """
@scope (.shell) to (.embedded) {
  .probe {
    color: rgb(125, 45, 120);
    background-color: rgb(215, 235, 220);
  }
}""",
    "S05": BODY + """
@scope (.shell) to (.embedded > *) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}""",
    "S06": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
  .embedded { color: rgb(20, 90, 110); }
}""",
    "S07": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}
#boundary { color: rgb(20, 90, 110); }""",
    "S08": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}
#boundary { color: unset; }""",
    "S09": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}
@scope (.embedded) {
  :scope { color: rgb(20, 90, 110); }
}""",
    "S10": BODY + """
@scope (.shell) to (.embedded) {
  :scope { color: rgb(125, 45, 120); }
  .probe { background-color: rgb(215, 235, 220); }
}""",
}

The expected values must also be literal and independent:

EXPECTED = {
    "S01": {"owned": (BASE, CLEAR), "boundary": (BASE, CLEAR),
            "inner": (BASE, CLEAR), "outside": (BASE, CLEAR)},
    "S02": {"owned": (OUTER, MARK), "boundary": (OUTER, MARK),
            "inner": (OUTER, MARK), "outside": (BASE, CLEAR)},
    "S03": {"owned": (OUTER, MARK), "boundary": (OUTER, CLEAR),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
    "S04": {"owned": (OUTER, MARK), "boundary": (BASE, CLEAR),
            "inner": (BASE, CLEAR), "outside": (BASE, CLEAR)},
    "S05": {"owned": (OUTER, MARK), "boundary": (OUTER, MARK),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
    "S06": {"owned": (OUTER, MARK), "boundary": (OUTER, CLEAR),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
    "S07": {"owned": (OUTER, MARK), "boundary": (INNER, CLEAR),
            "inner": (INNER, CLEAR), "outside": (BASE, CLEAR)},
    "S08": {"owned": (OUTER, MARK), "boundary": (OUTER, CLEAR),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
    "S09": {"owned": (OUTER, MARK), "boundary": (INNER, CLEAR),
            "inner": (INNER, CLEAR), "outside": (BASE, CLEAR)},
    "S10": {
        "limit-present-before": {
            "owned": (OUTER, MARK), "boundary": (OUTER, CLEAR),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
        "limit-removed": {
            "owned": (OUTER, MARK), "boundary": (OUTER, MARK),
            "inner": (OUTER, MARK), "outside": (BASE, CLEAR)},
        "limit-restored": {
            "owned": (OUTER, MARK), "boundary": (OUTER, CLEAR),
            "inner": (OUTER, CLEAR), "outside": (BASE, CLEAR)},
    },
}

Notice what is absent: no expected color is obtained by calling getComputedStyle() on a parent. Doing that would make the observation under test feed the oracle.

Prove selector exclusion separately from inherited color

S01 establishes the baseline. With only body { color: rgb(30, 30, 30); }, all four probes are expected to resolve to BASE, and their own background-color values are expected to resolve to transparent black, serialized here as rgba(0, 0, 0, 0). No scoped selector exists.

S02 establishes an active positive @scope control:

body {
  color: rgb(30, 30, 30);
}

@scope (.shell) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }
}

With no lower limit, #shell receives OUTER. Every .probe beneath it is selector-eligible for the marker, so #owned, #boundary and #inner are independently expected to receive MARK. Their text is expected to use OUTER: #owned inherits it from #shell; #boundary also inherits from the shell; #inner continues through its parent. #outside remains BASE/CLEAR.

S03 changes one scope input:

body {
  color: rgb(30, 30, 30);
}

@scope (.shell) to (.embedded) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }
}

The Level 6 scoped-style definition makes .embedded a lower limit. Because being in scope requires not being an inclusive descendant of that limit, both the matched limit element and its descendants are excluded from the containing scope. CSS Cascading and Inheritance Level 6 is the primary definition used for this expectation.

Therefore the marker should disappear from both #boundary and #inner. #owned should retain it. This is the evidence that distinguishes selector reach from color inheritance.

background-color works well for this supporting control because it is not inherited and its initial value is transparent. The W3C Backgrounds and Borders specification explicitly notes that background properties are not inherited and that an ancestor’s painted background can nevertheless show through a child whose own background is transparent. CSS Backgrounds and Borders Level 3 defines background-color as non-inherited with an initial transparent value.

That distinction is why the test compares the resolved scalar from the child rather than judging the screenshot. A transparent child drawn over a green ancestor could look green while its own backgroundColor remains rgba(0, 0, 0, 0). Appearance through transparency is not inheritance.

The core S03 pattern can be summarized as:

body              color BASE
└─ #shell          directly receives OUTER from scoped :scope rule
   ├─ #owned       eligible for scoped .probe -> MARK
   │               inherits OUTER
   └─ #boundary    LOWER LIMIT: not eligible for scoped .probe
      │            nevertheless inherits OUTER from #shell
      └─ #inner    outside outer scope
                   inherits OUTER through #boundary

#outside           remains BASE, outside scope root

This directly answers why text keeps its color. The scope boundary controls scoped selector matching. It does not alter the parent-child relationship that the inheritance algorithm follows.

CSS Cascading and Inheritance Level 5 states that inheritance propagates property values from parent elements to children and defines an element’s inherited value as the computed value of its parent. CSS Cascading and Inheritance Level 5 also notes that inherited properties use inheritance when the cascade supplies no value for the child.

The key sequence in S03 is therefore:

  1. The scoped :scope rule is eligible to style #shell, so the shell gets OUTER.

  2. The lower limit excludes #boundary and #inner from selector matching by the rules inside the outer @scope.

  3. No direct color declaration in the restricted fixture replaces the color on #boundary.

  4. Because color is inherited, the boundary takes the parent’s computed OUTER value.

  5. #inner in turn inherits OUTER from #boundary.

Chrome’s implementation guidance explicitly illustrates this “donut scope” result with color: a scoped root receives the color and nodes beyond the lower boundary continue to inherit it. Chrome for Developers: Limit the reach of your selectors with the CSS @scope at-rule describes this as selector isolation rather than style isolation. It is useful implementation-author guidance, not proof that an unexecuted browser build produced this fixture’s values.

S04 is the mechanism-discrimination control:

body {
  color: rgb(30, 30, 30);
}

@scope (.shell) to (.embedded) {
  .probe {
    color: rgb(125, 45, 120);
    background-color: rgb(215, 235, 220);
  }
}

Now OUTER is placed only on eligible .probe elements. #owned should receive it directly. #boundary and #inner are outside selector reach and therefore have no OUTER-valued ancestor created by the scoped root rule. They should fall back to the inherited BASE chain.

That changed-one-input comparison is more informative than finding the same purple scalar twice. S03 says, “excluded nodes are OUTER”; S04 says, “when the shell’s OUTER input is removed while the lower limit remains, those excluded nodes become BASE.” Under the deliberately constrained declaration set, that supports inheritance from the styled root as the explanation.

S05 moves only the lower-limit selector:

@scope (.shell) to (.embedded > *) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }
}

Now the scope limit is any child matching .embedded > *. In this fixed DOM, #inner matches that limit while #boundary does not. Therefore #boundary becomes part of the outer scope and should receive MARK; #inner remains excluded and should remain CLEAR. Both should still use OUTER because neither change severs the ancestry through which color inherits.

This is the operational difference between a lower limit of .embedded and .embedded > *. It is a scope-membership control, not a specificity contest, and this playbook deliberately does not expand into the separate scope-proximity ordering questions present in the evolving Level 6 draft.

Evaluate repairs, negative controls and class-change regressions

S06 tests a tempting but structurally impossible repair:

@scope (.shell) to (.embedded) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }

  .embedded {
    color: rgb(20, 90, 110);
  }
}

The declaration looks locally appropriate, but its location is wrong. .embedded is the lower limit of the very scope that contains the rule. Under the fixture’s scope definition, the boundary is excluded from the rule’s selector reach. The expected outcome remains OUTER/CLEAR for both boundary and inner.

Keep S06 in regression evidence after repairing the component. A failed candidate is useful because it demonstrates that “we added the right value” is insufficient when the selector cannot reach the owner that must receive it.

S07 supplies the smallest explicit boundary repair:

@scope (.shell) to (.embedded) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }
}

#boundary {
  color: rgb(20, 90, 110);
}

The outer scope is unchanged. The marker should still stop at the boundary, showing that outer selector reach has not been widened. Independently, the unscoped boundary declaration directly supplies INNER to #boundary; #inner inherits INNER from it. #owned remains OUTER/MARK, and #outside remains BASE/CLEAR.

This is the central component-boundary repair pattern: give the embedded owner a deliberate value at a location whose selector can actually select it. It changes the inheritance input without weakening the outer lower limit.

S09 expresses the same ownership policy with a separate scope:

@scope (.shell) to (.embedded) {
  :scope {
    color: rgb(125, 45, 120);
  }

  .probe {
    background-color: rgb(215, 235, 220);
  }
}

@scope (.embedded) {
  :scope {
    color: rgb(20, 90, 110);
  }
}

The outer scope remains bounded. The second scope establishes #boundary as its own root, whose :scope declaration supplies INNER. The inner paragraph then inherits that color. In this deliberately restricted fixture, no competing outer scoped rule directly matches the excluded boundary, so this case does not require deciding any scope-proximity dispute.

S08 is the negative repair control:

#boundary {
  color: unset;
}

For an inherited property, unset does not mean “isolate me from my parent.” Cascade Level 5 defines unset as inherit for inherited properties and initial for non-inherited properties. CSS Cascading and Inheritance Level 5 therefore supports the expectation that #boundary continues taking OUTER, and #inner continues inheriting from it.

That control prevents a common overcorrection: reaching for CSS-wide reset keywords without checking their property-specific semantics. This playbook does not recommend blanket resets. S07 and S09 establish only a local color contract; they do not isolate every inherited property.

S10 turns the boundary class into a regression trigger. Start from S03, then run three explicit phases in one fresh document:

// Phase A: lower limit is present.
capture("limit-present-before");

// Phase B: remove only the lower-limit class.
document.querySelector("#boundary").classList.remove("embedded");
capture("limit-removed");

// Phase C: restore it.
document.querySelector("#boundary").classList.add("embedded");
capture("limit-restored");

No arbitrary sleep is part of the contract. Each mutation is synchronous, and each measurement is explicitly taken after the mutation. A production harness may still await the page’s own readiness conditions before beginning, but this fixture contains no animations, transitions, network dependencies or application schedulers.

The predicted discriminator is the marker. Phase A should be OUTER/CLEAR on boundary and inner. Removing embedded removes the matching lower limit, so in Phase B both .probe nodes become eligible and should be OUTER/MARK. Restoring the class should restore OUTER/CLEAR in Phase C. Color stays OUTER through all three phases because the shell remains its inherited source.

A class refactor can therefore change outer selector eligibility without changing the inherited color. That is exactly why a green-looking text sample cannot validate the boundary by itself.

Collect primitive evidence and make the evaluator reject incomplete runs

getComputedStyle() is appropriate here for resolved scalar collection, provided the target is connected and belongs to a rendered document. The CSSOM draft defines the returned declaration in terms of resolved values and places conditions on connected elements in a rendered browsing context. CSS Object Model Level 1 also distinguishes resolved values from the specification concept of computed values.

It does not provide a provenance report saying “this source rule won.” A copied color value is evidence about the resolved output. Source attribution in this laboratory is an inference supported by the intentionally tiny candidate set, the literal stylesheet, DOM ancestry and changed-one-input controls. Equal values from unrelated declarations would weaken that inference.

Also copy primitive strings immediately:

function readNode(id) {
  const el = document.getElementById(id);
  const style = getComputedStyle(el);

  return {
    id,
    color: String(style.color),
    backgroundColor: String(style.backgroundColor)
  };
}

Do not retain the live style object as a historical snapshot and inspect it after later mutations.

The following Playwright runner is designed as an executable starting point. It creates a fresh page per primary case, checks required element cardinality and stylesheet parsing, captures environment identity, and special-cases S10’s three phases. The output path should be unique per run so a new attempt cannot overwrite earlier evidence.

from future import annotations

import hashlib
import json
import os
import platform
import sys
from datetime import datetime, timezone
from pathlib import Path

import playwright
from playwright.sync_api import sync_playwright

NODE_IDS = ("shell", "owned", "boundary", "inner", "outside")
PROBE_IDS = ("owned", "boundary", "inner", "outside")

HTML_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS @scope inheritance fixture</title>
<style id="under-test">
__CSS__
</style>
</head>
<body>
<div id="shell" class="shell">
  <p id="owned" class="probe">Owned text</p>
  <section id="boundary" class="embedded probe">
    Embedded boundary
    <p id="inner" class="probe">Embedded inner text</p>
  </section>
</div>
<p id="outside" class="probe">Outside text</p>
</body>
</html>
"""

# CASE_CSS and EXPECTED are the independent literals shown earlier.
# Paste those two dictionaries here unchanged.

def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()

def sha256_text(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()

def build_html(css: str) -> str:
    return HTML_TEMPLATE.replace("__CSS__", css)

def collect_page(page, case_id: str, phase: str, fixture_digest: str,
                 literal_css: str, browser_version: str,
                 executable_path: str, launch_options: dict) -> dict:
    return page.evaluate(
        """args => {
          const required = ["shell","owned","boundary","inner","outside"];
          const probes = ["owned","boundary","inner","outside"];

          const cardinality = Object.fromEntries(required.map(id => [
            id, document.querySelectorAll("#" + id).length
          ]));

          const stylesheet = document.getElementById("under-test");
          const sheet = stylesheet && stylesheet.sheet;
          let parsedRules = null;
          let parseReadable = false;
          try {
            parsedRules = sheet ? Array.from(sheet.cssRules, r => r.cssText) : null;
            parseReadable = Array.isArray(parsedRules);
          } catch (_) {}

          const nodes = Object.fromEntries(probes.map(id => {
            const el = document.getElementById(id);
            const cs = getComputedStyle(el);
            const ancestry = [];
            for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
              ancestry.push({
                tag: n.tagName.toLowerCase(),
                id: n.id || "",
                classes: Array.from(n.classList)
              });
            }
            return [id, {
              color: String(cs.color),
              backgroundColor: String(cs.backgroundColor),
              connected: Boolean(el.isConnected),
              classes: Array.from(el.classList),
              ancestry
            }];
          }));

          return {
            cardinality,
            parsedStylesheetPresent: Boolean(sheet && parseReadable),
            parsedRules,
            renderedDocument: document.visibilityState !== "prerender",
            forcedColorsActive:
              matchMedia("(forced-colors: active)").matches,
            nodes
          };
        }""",
        {}
    ) | {
        "case": case_id,
        "phase": phase,
        "fixtureDigest": fixture_digest,
        "literalStylesheet": literal_css,
        "scopeRootSelector": ".shell" if "@scope" in literal_css else None,
        "scopeLimitSelector": (
            ".embedded > " if "to (.embedded > )" in literal_css
            else ".embedded" if "to (.embedded)" in literal_css
            else None
        ),
        "browserVersion": browser_version,
        "executablePath": executable_path,
        "pythonVersion": sys.version,
        "playwrightPackage": getattr(playwright, "__version__", "unknown"),
        "operatingSystem": platform.platform(),
        "architecture": platform.machine(),
        "launchOptions": launch_options,
        "startedAt": None,  # caller sets real timestamps
        "capturedAt": utc_now(),
    }

def validate_structure(record: dict) -> None:
    for node_id in NODE_IDS:
        if record["cardinality"].get(node_id) != 1:
            raise AssertionError(
                f"{record['case']} {record['phase']}: "
                f"cardinality for {node_id} is not 1"
            )
    if not record["parsedStylesheetPresent"]:
        raise AssertionError(
            f"{record['case']} {record['phase']}: stylesheet not readable"
        )
    for node_id in PROBE_IDS:
        if not record["nodes"][node_id]["connected"]:
            raise AssertionError(
                f"{record['case']} {record['phase']}: {node_id} disconnected"
            )

def expected_for(case_id: str, phase: str):
    value = EXPECTED[case_id]
    if case_id == "S10":
        return value[phase]
    return value

def compare_record(record: dict) -> dict:
    expected = expected_for(record["case"], record["phase"])
    comparisons = {}
    ok = True

    for node_id in PROBE_IDS:
        expected_color, expected_bg = expected[node_id]
        observed = record["nodes"][node_id]
        node_ok = (
            observed["color"] == expected_color
            and observed["backgroundColor"] == expected_bg
        )
        comparisons[node_id] = {
            "expectedColor": expected_color,
            "expectedBackgroundColor": expected_bg,
            "observedColor": observed["color"],
            "observedBackgroundColor": observed["backgroundColor"],
            "match": node_ok,
        }
        ok = ok and node_ok

    record["independentExpectedValues"] = expected
    record["comparisonStatus"] = "MATCH" if ok else "MISMATCH"
    record["comparisons"] = comparisons
    return record

def main():
    run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
    out = Path(f"scope-evidence-{run_id}.json")

    launch_options = {"headless": True}
    ledger = {
        "status": "COLLECTION_IN_PROGRESS",
        "runId": run_id,
        "records": [],
    }

    with sync_playwright() as p:
        browser_type = p.chromium
        executable_path = browser_type.executable_path
        browser = browser_type.launch(**launch_options)

        try:
            browser_version = browser.version

            for case_id in [f"S{i:02d}" for i in range(1, 11)]:
                css = CASE_CSS[case_id]
                html = build_html(css)
                digest = sha256_text(html)
                started = utc_now()

                page = browser.new_page()
                try:
                    page.set_content(html, wait_until="load")

                    phases = ["single"]
                    if case_id == "S10":
                        phases = [
                            "limit-present-before",
                            "limit-removed",
                            "limit-restored",
                        ]

                    for phase in phases:
                        if case_id == "S10" and phase == "limit-removed":
                            page.eval_on_selector(
                                "#boundary",
                                "el => el.classList.remove('embedded')"
                            )
                        elif case_id == "S10" and phase == "limit-restored":
                            page.eval_on_selector(
                                "#boundary",
                                "el => el.classList.add('embedded')"
                            )

                        record = collect_page(
                            page, case_id, phase, digest, css,
                            browser_version, executable_path, launch_options
                        )
                        record["startedAt"] = started
                        validate_structure(record)
                        ledger["records"].append(compare_record(record))
                finally:
                    page.close()

            ledger["status"] = "COLLECTION_COMPLETE"
        finally:
            browser.close()

    out.write_text(json.dumps(ledger, indent=2), encoding="utf-8")
    print(out)

if name == "__main__":
    main()

The runner should additionally reject unsupported @scope syntax before an inheritance conclusion is drawn. A practical commissioning extension is to inspect the positive-control record for S02 and require that the parsed stylesheet contains an @scope rule and that the expected marker reaches at least #owned. If the selected runtime silently ignores the syntax, the outcome is HOLD, not “the browser disproved inheritance.”

Forced-colors state is recorded rather than changed. The fixture itself contains no animation or transition behavior and does not change accessibility preferences. If an environmental override materially changes the literal-color experiment, preserve it in the ledger and classify the run according to the release policy rather than disabling the user’s setting.

The evaluator also needs a synthetic self-test. This check is separate from browser observations:

def checker_self_test():
    good = {
        "case": "S03",
        "phase": "single",
        "nodes": {
            "owned": {
                "color": OUTER,
                "backgroundColor": MARK,
            },
            "boundary": {
                "color": OUTER,
                "backgroundColor": CLEAR,
            },
            "inner": {
                "color": OUTER,
                "backgroundColor": CLEAR,
            },
            "outside": {
                "color": BASE,
                "backgroundColor": CLEAR,
            },
        },
    }

    assert compare_record(json.loads(json.dumps(good)))["comparisonStatus"] == "MATCH"

    missing_node = json.loads(json.dumps(good))
    del missing_node["nodes"]["inner"]
    try:
        compare_record(missing_node)
        raise AssertionError("checker accepted a missing node")
    except KeyError:
        pass

    wrong_background = json.loads(json.dumps(good))
    wrong_background["nodes"]["boundary"]["backgroundColor"] = MARK
    assert (
        compare_record(wrong_background)["comparisonStatus"]
        == "MISMATCH"
    )

    missing_phase = json.loads(json.dumps(good))
    missing_phase["case"] = "S10"
    missing_phase["phase"] = "single"
    try:
        compare_record(missing_phase)
        raise AssertionError("checker accepted an unknown S10 phase")
    except KeyError:
        pass

A productionized evaluator should also assert the exact case set {S01...S10}, reject duplicate case/phase keys, require one record each for S01-S09 and exactly three S10 records, and fail closed when any required field is absent.

The evidence ledger schema should preserve the following fields for every row:

Field

Why it is required

Current article value

case / phase

Prevents ambiguous or missing scenarios

S01-S10 defined; observations not collected

fixture digest

Binds result to exact rendered fixture bytes

not collected

literal stylesheet

Preserves actual controlled CSS input

authored above; runtime copy not collected

DOM ancestry/classes

Makes boundary and inheritance path auditable

expected structure authored; runtime not collected

scope root / limit selectors

Records selector-boundary inputs

authored per case

parsed stylesheet presence

Detects ignored or unreadable CSS

not collected

browser/build

Identifies actual engine

not collected

executable path

Detects unintended packaged/system browser

not collected

Python/Playwright identity

Records harness runtime

proposed only; actual not collected

OS / architecture

Records host environment

not collected

launch options

Records execution mode and flags

not collected

forced-colors state

Records relevant environmental override

not collected

copied color

Primitive resolved scalar

not collected

copied backgroundColor

Primitive non-inherited control scalar

not collected

independent expected values

Keeps oracle separate from observation

authored above

comparison status

MATCH/MISMATCH only after complete collection

NOT EXECUTED

run timestamps

Distinguishes separate executions

not collected

The article-level blank observed-results ledger is therefore:

Case / phase

Expected color/background result

Observed

Comparison

Runtime state

S01 / single

manifest above

not collected

NOT EXECUTED

HOLD

S02 / single

manifest above

not collected

NOT EXECUTED

HOLD

S03 / single

manifest above

not collected

NOT EXECUTED

HOLD

S04 / single

manifest above

not collected

NOT EXECUTED

HOLD

S05 / single

manifest above

not collected

NOT EXECUTED

HOLD

S06 / single

manifest above

not collected

NOT EXECUTED

HOLD

S07 / single

manifest above

not collected

NOT EXECUTED

HOLD

S08 / single

manifest above

not collected

NOT EXECUTED

HOLD

S09 / single

manifest above

not collected

NOT EXECUTED

HOLD

S10 / limit-present-before

manifest above

not collected

NOT EXECUTED

HOLD

S10 / limit-removed

manifest above

not collected

NOT EXECUTED

HOLD

S10 / limit-restored

manifest above

not collected

NOT EXECUTED

HOLD

Checker self-test

reject missing node, wrong marker, missing S10 phase

not executed

NOT EXECUTED

HOLD

One color scalar cannot identify its source declaration in the general case. Two rules may resolve to identical RGB values; inheritance, user styles or other author declarations could also converge on the same scalar. CSSOM’s resolved-value contract is about the value, not why that value won.

The inference here is narrower: only a documented candidate set is admitted; the DOM is fixed; stylesheets are literal; S03 versus S04 removes one inherited input; S02/S03/S05/S10 move selector eligibility while preserving the color source; and the non-inherited marker changes independently. That collection can support the bounded explanation without pretending to be a universal rule-provenance API.

Recover safely, revalidate the approved revision and make the release decision

A repair should not erase the failing evidence that justified it. Preserve every ledger under a unique run identifier and keep the literal stylesheet and fixture digest beside it. If S03 demonstrates the expected mechanism but violates the reviewed embedded-color policy, retain that record before testing S07 or S09.

A safe recovery sequence is:

  1. Freeze the failed candidate’s fixture, manifest, ledger and runtime metadata. Never rewrite its expected values to fit an observation.

  2. Restore the known DOM and stylesheet for the intended baseline. Recompute the fixture digest from the actual rendered input rather than copying an old hash.

  3. Reconfirm the product policy. If the embedded component is intentionally themed by the shell, OUTER may be acceptable and no color repair is required. If its reviewed policy is INNER, select an authorized boundary-owning declaration such as S07 or an embedded scope such as S09.

  4. Start fresh rendered pages for every case. Do not reuse a page whose stylesheet or classes were modified by a previous case.

  5. Run S01-S10 in full. Do not run only the repaired case: S02 is the positive scope control; S04 identifies the inherited input; S06 proves the rejected repair remains rejected; S08 proves unset does not create the desired boundary; and S10 protects against class regressions.

  6. Execute the checker self-test separately. A browser ledger cannot compensate for an evaluator that accepts incomplete evidence.

  7. Reconcile actual runtime identity. A changed executable, browser version, OS, architecture, Playwright package or material launch option means the evidence belongs to a new baseline.

  8. Keep browser and page cleanup in finally blocks. Resource cleanup is part of making reruns deterministic, not evidence about CSS semantics.

  9. Write the new ledger to a new file. Never replace the prior failed ledger.

Separate layout-oriented debugging from this color mechanism. Refonte’s article on ancestor styles and fixed-overlay geometry uses ancestor relationships to answer a containing-block question, but its rectangle evidence does not bear on inherited color. Its own methodology similarly keeps independently authored expectations separate from measured geometry.

Likewise, content-visibility layout-size validation belongs to containment and skipped-rendering regression work rather than this scope-boundary laboratory. That page explicitly treats lifecycle and geometry evidence as separate acceptance concerns.

The final gate uses four states:

Decision

Required evidence

Meaning here

ACCEPT

Complete S01-S10 ledger; all required nodes and S10 phases present; parsed-scope positive control succeeds; comparator self-test succeeds; observations match the independent manifest; actual runtime identity is recorded; and the reviewed embedded-component policy is satisfied by the candidate revision.

The bounded color contract is supported for the recorded runtime and fixture.

REPAIR

Mechanism evidence is coherent, but the candidate violates the reviewed product policy, for example S03 produces outer inherited color where INNER is required, or S06 attempts a declaration that cannot select the boundary.

Change the component-boundary declaration, then rerun all cases.

RERUN

Collection is contaminated, a runtime or fixture revision changed, a ledger was produced with the wrong executable, or a corrected candidate has not yet been run against the complete manifest.

Produce a new immutable ledger under the revised conditions.

HOLD

Browser syntax support is unknown or absent; stylesheet parsing is not demonstrated; required cases, nodes or phases are missing; comparator self-test fails; contradictions remain unresolved; or no browser observations exist.

Do not infer release acceptance.

For this article’s current state, the decision is HOLD. Every primary case remains EXPECTED / NOT EXECUTED and all observed values are not collected.

A runtime that ignores the selected @scope syntax must not be allowed to masquerade as an inheritance finding. S02 is therefore more than a convenience baseline: it is an active positive control showing that the runtime parsed and applied scoped rules in the fixture. Failure to establish that control means HOLD.

The repair’s integration limit is equally important. S07 or S09 can support a conclusion about this component’s color inheritance boundary. They do not prove complete CSS style isolation. Other inherited properties have their own contracts; non-inherited properties have different defaulting behavior; and the article deliberately says nothing about Shadow DOM, slots, framework-generated scoping, containment, positioning or security boundaries.

Transition-specific acceptance must also stay outside this gate. If a component later adds an entry transition, use dedicated entry-transition validation with @starting-style rather than adding timing to this static inheritance fixture. That separate Refonte playbook records lifecycle events and uses its own release criteria.

Ownership should be explicit. The component owner approves whether the embedded component intentionally inherits OUTER or requires INNER. The shared-style or design-system owner reviews the outer scope root, lower-limit selector and any reusable boundary policy. The test owner maintains the literal manifest, runtime pinning, checker and immutable ledger format. The release owner makes the ACCEPT / REPAIR / RERUN / HOLD decision from the complete evidence rather than from screenshots or one copied color.

The underlying diagnosis is now narrow enough to be operational: an @scope lower limit can correctly stop scoped selector matching while inherited color continues through DOM ancestry. The evidence supporting a safe repair is not “the text became teal.” It is the complete pattern: marker reach changes when scope eligibility changes; color survives while the outer root remains its inheritance source; color falls back when that source is removed; an ineligible repair fails; a boundary-owning declaration or separate embedded scope supplies INNER without widening the outer selector reach; outside content remains untouched; and an independent evaluator rejects incomplete or contradictory records.

Strengthen frontend debugging with Refonte Learning

The same discipline scales beyond this fixture: define ownership before measurement, keep expected values independent of observations, preserve runtime identity and require controls that can falsify the preferred explanation.

For engineers seeking broader structured foundations, the Refonte Learning - FrontEnd Developer Program currently lists a four-month program at 10–12 hours per week, asks for basic programming concepts with HTML/CSS familiarity as a plus, and separately states that applicants must be working toward a bachelor’s or higher-level degree. Its published topics include HTML5/CSS3, JavaScript, responsive design, React, Git, accessibility, performance and practical project work; the page also describes mentor guidance, “Potential Internship,” and Training Certificate and Certificate of Internship outcomes upon successful completion.

That page does not establish that this specific @scope laboratory, Playwright workflow, browser-version matrix or component-isolation assessment is part of its syllabus. Treat the program as an optional route to broader frontend foundations, not as evidence for the specialist experiment described here.